Pretty-Printing JSON with PHP Pretty-Printing JSON with PHP php php

Pretty-Printing JSON with PHP


PHP 5.4 offers the JSON_PRETTY_PRINT option for use with the json_encode() call.

http://php.net/manual/en/function.json-encode.php

<?php...$json_string = json_encode($data, JSON_PRETTY_PRINT);


This function will take JSON string and indent it very readable. It also should be convergent,

prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )

Input

{"key1":[1,2,3],"key2":"value"}

Output

{    "key1": [        1,        2,        3    ],    "key2": "value"}

Code

function prettyPrint( $json ){    $result = '';    $level = 0;    $in_quotes = false;    $in_escape = false;    $ends_line_level = NULL;    $json_length = strlen( $json );    for( $i = 0; $i < $json_length; $i++ ) {        $char = $json[$i];        $new_line_level = NULL;        $post = "";        if( $ends_line_level !== NULL ) {            $new_line_level = $ends_line_level;            $ends_line_level = NULL;        }        if ( $in_escape ) {            $in_escape = false;        } else if( $char === '"' ) {            $in_quotes = !$in_quotes;        } else if( ! $in_quotes ) {            switch( $char ) {                case '}': case ']':                    $level--;                    $ends_line_level = NULL;                    $new_line_level = $level;                    break;                case '{': case '[':                    $level++;                case ',':                    $ends_line_level = $level;                    break;                case ':':                    $post = " ";                    break;                case " ": case "\t": case "\n": case "\r":                    $char = "";                    $ends_line_level = $new_line_level;                    $new_line_level = NULL;                    break;            }        } else if ( $char === '\\' ) {            $in_escape = true;        }        if( $new_line_level !== NULL ) {            $result .= "\n".str_repeat( "\t", $new_line_level );        }        $result .= $char.$post;    }    return $result;}


Many users suggested that you use

echo json_encode($results, JSON_PRETTY_PRINT);

Which is absolutely right. But it's not enough, the browser needs to understand the type of data, you can specify the header just before echo-ing the data back to the user.

header('Content-Type: application/json');

This will result in a well formatted output.

Or, if you like extensions you can use JSONView for Chrome.