简体   繁体   中英

JSON pretty print without use json_decode in php

For example i have json strings like this ( from the first place ). And It's not formatted.

{"data":[{"id":"14","memo_kondisi":"Kekurangan pekerjaan","total_row":"5","nilai_temuan":"1.000.000","data_sebab":[{"id":"15","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[{"id":"25","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"},{"id":"26","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"},{"id":"31","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"}]},{"id":"16","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[{"id":"34","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"},{"id":"35","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"}]}]},{"id":"15","memo_kondisi":"Kekurangan pekerjaan","total_row":"2","nilai_temuan":"1.000.000","data_sebab":[{"id":"5","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data _rekomendasi":[]},{"id":"10","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]}]},{"id":"16","memo_kondisi":"","total_row":"2","nilai_temuan":"0","data_sebab":[{"id":"9","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]},{"id":"12","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]}]}]}

I see some similar question that you have to use json_decode and i have to encode again and using json_encode($json,JSON_PRETTY_PRINT)

Is there a way for make json readable without decode the JSON first and encode it again in PHP ?

Note : I expect the result is still in JSON

Only a parser can understand the JSON, so you can either do what you proposed or write your own parser. If you have access to the origin of the JSON, make it pretty in the first place.

Not really. Using someone else's parser lib won't make any difference, as they'll call json_decode() too.

You could create a little function that you could call:

function prettify($json)
{
    $array = json_decode($json, true);
    $json = json_encode($array, JSON_PRETTY_PRINT);
    return $json;
}

Then echo prettify($jsonString); would be easier than constantly decoding and re-encoding. See here https://3v4l.org/CcJlf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM