Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

json from file to file in same style in oneline per line

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading