i wanna convert a json file has text like this design json_text
https://phponlines.com/result/e2j9RgRnm7
$json_text = '
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]';
$json_decoded = json_decode($json_text, true);
var_dump(json_encode($json_decoded));
then after i edit it to get same design again but i get different deisng instead in one line
[{"id":"1","name":"john","bd":[]},{"id":"2","name":"gary","bd":[1,2]}]
but what i want is
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]
CodePudding user response:
As stated in my comments above, this is not particularly advisable, and writing any portion of a JSON file by hand is even more inadvisable.
But if you do not wish to see the light, then at least the use the minimal amount of darkness.
// polyfill for PHP<8.1
if (!function_exists('array_is_list')) {
function array_is_list(array $a) {
return $a === [] || (array_keys($a) === range(0, count($a) - 1));
}
}
function do_weird_json(array $input) {
if( ! array_is_list($input) ) {
throw new Exception('Input data must be a list');
}
return sprintf("[\n%s\n]\n", implode(",\n", array_map('json_encode', $input)));
}
$json_text = '
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]';
$json_decoded = json_decode($json_text, true);
$json_decoded[1]['name'] = 'bill';
var_dump(do_weird_json($json_decoded));
Output:
string(74) "[
{"id":"1","name":"john","bd":[]},
{"id":"2","name":"bill","bd":[1,2]}
]
"
Again, the best thing to do would be to leave the JSON as the default, not-human-friendly format and use a client-side tool like jq
, etc to reformat the JSON for you for viewing purposes.