开发者

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

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开发者_JAVA百科 and spaced to make it easier to read.


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
        }
    }
}


json_encode($response, JSON_PRETTY_PRINT);

It's 2017 and I think this should be the answer for anyone on a modern version of PHP.

Note that lots of options exist for how to encode the JSON string to your liking. From php.net: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR


echo '<pre>';
print_r(json_decode($response));
echo '</pre>';

Too simple?


Pipe it through python -mjson.tool.


The suggestion of using python worked well for me. Here's some code to use this from PHP:

function jsonEncode( $data, $pretty = false ) {
    $str = json_encode($data);
    if( $pretty ) {
        $descriptorSpec = array(
                0 => array('pipe', 'r'),  // stdin is a pipe that the child will read from
                1 => array('pipe', 'w'),  // stdout is a pipe that the child will write to
        );
        $fp = proc_open('/usr/bin/python -mjson.tool', $descriptorSpec, $pipes);
        fputs($pipes[0], $str);
        fclose($pipes[0]);
        $str = '';
        while( !feof($pipes[1]) ) {
            $str .= $chunk = fgets($pipes[1], 1024);
        }
        fclose($pipes[1]);
    }
    return $str;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜