Human Readable JSON: aka Add spaces and breaks to json dump

kylex picture kylex · Sep 12, 2011 · Viewed 17.6k times · Source

Is there a "simple" script somewhere that will take a json data and format it to make it more readable?

For example:

// $response is a json encoded string.
var_dump($response);

The above outputs everything on one line. I'd like for it to be indented and spaced to make it easier to read.

Answer

phihag picture phihag · Sep 12, 2011

Note that var_dump and its terser cousin var_export do print newlines.

Bear in mind that newlines are not shown in HTML document by default. In an HTML context, you want this instead:

echo '<div style="font-family: monospace; white-space:pre;">';
echo htmlspecialchars(var_export($response));
echo '</div>';

In php 5.4+, you can simply use the PRETTY_PRINT flag of json_encode:

echo json_encode($response, JSON_PRETTY_PRINT);

Again, in an HTML context, you'll have to wrap it as described above.