15

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.

kylex
  • 14,178
  • 33
  • 114
  • 175
  • 1
    If this is just for reading JSON, perhaps a browser addon like JSONView ([chrome](https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc), [firefox](https://addons.mozilla.org/en-US/firefox/addon/jsonview/), [opera](https://github.com/fearphage/jsonview-opera)) would be useful instead? (There are lots of other similar addons too.) – salathe Sep 12 '11 at 20:53

7 Answers7

21

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.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • 1
    @Matt Anderson Thanks, added a note that mentions a newer php is required, and added `var_export`. – phihag Sep 12 '11 at 20:47
  • cool trick, but I'm using 5.3 currently... I will keep it in mind for the future. – kylex Sep 12 '11 at 20:48
12

Paste it into JSONLint.com and click validate.

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • This seems to be the quickest easiest option... useful little tool. thanks! – kylex Sep 12 '11 at 20:47
  • My preference is this site: http://json.parser.online.fr/ That said, JavaScript has a nice JSON parsing function which performs this function. Would be nice to do have something similar in PHP too. – Anthony Jul 07 '15 at 18:58
11

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
        }
    }
}
som
  • 2,023
  • 30
  • 37
  • 1
    I loved this so much, I converted it to Java. Enjoy anyone who finds this. https://gist.github.com/PaulBGD/846d2c4503a7bfc5036a – PaulBGD Aug 18 '14 at 00:35
8

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

Matthew Marichiba
  • 1,942
  • 1
  • 23
  • 24
3
echo '<pre>';
print_r(json_decode($response));
echo '</pre>';

Too simple?

Makita
  • 1,812
  • 12
  • 15
0

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;
}
simon
  • 933
  • 1
  • 9
  • 17
0

Pipe it through python -mjson.tool.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275