Skip to content
Advertisement

Add a line break automatically after comma in JSON file?

I have a JSON file automatically generated from my PHP laravel backend, it’s just an array converted to JSON format, problem is I’d like to have a the JSON file row by row instead of this ugly mess of serialized data…

This is how my JSON file looks:

[{"cityName":"Toronto","provinceOrState":"Canada","country":"Canada"},{"cityName":"Montreal","provinceOrState":"Canada","country":"Canada"},{"cityName":"Calgary","provinceOrState":"Canada","country":"Canada"},{"cityName":"Ottawa","provinceOrState":"Canada","country":"Canada"},{"cityName":"Edmonton","provinceOrState":"Canada","country":"Canada"},{"cityName":"Mississauga","provinceOrState":"Canada","country":"Canada"},{"cityName":"North York",

If you past it into your IDE (mine is Visual Studio Code) you will see how ugly it looks, because of it syntax hilighting doesn’t even work…

Advertisement

Answer

json_encode() has a JSON_PRETTY_PRINT option. Something like this should work:

$json = '[{"cityName":"Toronto","provinceOrState":"Canada","country":"Canada"},{"cityName":"Montreal","provinceOrState":"Canada","country":"Canada"},{"cityName":"Calgary","provinceOrState":"Canada","country":"Canada"},{"cityName":"Ottawa","provinceOrState":"Canada","country":"Canada"},{"cityName":"Edmonton","provinceOrState":"Canada","country":"Canada"},{"cityName":"Mississauga","provinceOrState":"Canada","country":"Canada"}]';

$data = json_decode($json);
$json = json_encode($data, JSON_PRETTY_PRINT);

echo "<pre>$json</pre>";

This results in an output like this:

[
    {
        "cityName": "Toronto",
        "provinceOrState": "Canada",
        "country": "Canada"
    },
    {
        "cityName": "Montreal",
        "provinceOrState": "Canada",
        "country": "Canada"
    },
    ......
]
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement