I came up with this little trick to format JSON output for a little test tool I was making:

echo json_encode(json_decode($json_string), JSON_PRETTY_PRINT);

It seems a bit silly: converting to an array so that I can then apply the pretty-print parameter to json_encode(), but then it is likely more efficient than some user-defined function to figure out where to add newlines and tabs/spaces. I was just wondering if I was missing anything in the standard library somewhere that would get the same results from an unformatted JSON string -- or is this about as good as anything?

    I don't have a better solution, but would like to point out that there are no other json_* functions you can call that might be of use.

    You could try to get the JSON formatted at the source? But watch out because newlines in JSON code will break that json code for certain encoding/decoding libraries. I.e., pretty-printed JSON is not valid for certain functions.

      That decode/encode is probably the best available way to do it -- it just feels kind of stupid to me for some reason. 🙂 But then it is a display consideration, and PHP is not about client-side display, so . . . ¯_(&#12484😉_/¯

         echo json_encode(json_decode($json_string));
         echo $json_string;

        Would be another way,

        build arrays. convert to JSON and send.

          NogDog;11060685 wrote:

          That decode/encode is probably the best available way to do it -- it just feels kind of stupid to me for some reason. 🙂 But then it is a display consideration, and PHP is not about client-side display, so . . . ¯_(&#12484😉_/¯

          I would do it without a second thought. PHP built-in functions are probably fast and robust -- although you should probably check to make sure the original JSON is valid instead of just feeding on function result to the other?

          Googling around you'll find plenty of little dinky libraries. I tend not to trust dinky little libraries. Only use them if there's nothing else.
          https://gist.github.com/GloryFish/1045396

          Also, the popular stackoverflow answer likes your solution too:
          http://stackoverflow.com/questions/6054033/pretty-printing-json-with-php

            Write a Reply...