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

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


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.


Paste it into JSONLint.com and click validate.


Had a similar problem, in that I was posting a serialised javascript object to a php script and wished to save it to the server in a human-readable format.

Found this post on the webdeveloper.com forum and tweaked the code very slightly to suit my own sensibilities (it takes a json encoded string):

function jsonToReadable($json){    $tc = 0;        //tab count    $r = '';        //result    $q = false;     //quotes    $t = "\t";      //tab    $nl = "\n";     //new line    for($i=0;$i<strlen($json);$i++){        $c = $json[$i];        if($c=='"' && $json[$i-1]!='\\') $q = !$q;        if($q){            $r .= $c;            continue;        }        switch($c){            case '{':            case '[':                $r .= $c . $nl . str_repeat($t, ++$tc);                break;            case '}':            case ']':                $r .= $nl . str_repeat($t, --$tc) . $c;                break;            case ',':                $r .= $c;                if($json[$i+1]!='{' && $json[$i+1]!='[') $r .= $nl . str_repeat($t, $tc);                break;            case ':':                $r .= $c . ' ';                break;            default:                $r .= $c;        }    }    return $r;}

passing in

{"object":{"array":["one","two"],"sub-object":{"one":"string","two":2}}}

returns

{    "object": {        "array": [            "one",            "two"        ],        "sub-object": {            "one": "string",            "two": 2        }    }}