Pretty Print JSON

We can use function json_print() to explore JSON data, since JSON has no spacing or indentation. The function json_print() make JSON data to display in the human-readable format.

<?php

function json_print($json) {

    $result      = '';
    $pos         = 0;
    $strLen      = strlen($json);
    $indentStr   = '  ';
    $newLine     = "\n";
    $prevChar    = '';
    $outOfQuotes = true;

    for ($i=0; $i<=$strLen; $i++) {

        // Grab the next character in the string.
        $char = substr($json, $i, 1);

        // Put spaces in front of :
        if ($outOfQuotes && $char == ':' && $prevChar != ' ') {
            $result .= ' ';
        }

        if ($outOfQuotes && $char != ' ' && $prevChar == ':') {
            $result .= ' ';
        }

        // Are we inside a quoted string?
        if ($char == '"' && $prevChar != '\\') {
            $outOfQuotes = !$outOfQuotes;

            // If this character is the end of an element, 
            // output a new line and indent the next line.
        } else if(($char == '}' || $char == ']') && $outOfQuotes) {
            $result .= $newLine;
            $pos --;
            for ($j=0; $j<$pos; $j++) {
                $result .= $indentStr;
            }
        }

        // Add the character to the result string.
        $result .= $char;

        // If the last character was the beginning of an element, 
        // output a new line and indent the next line.
        if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
            $result .= $newLine;
            if ($char == '{' || $char == '[') {
                $pos ++;
            }

            for ($j = 0; $j < $pos; $j++) {
                $result .= $indentStr;
            }
        }

        $prevChar = $char;
    }

    return $result;
}

// Uses....

//........
//........

echo json_print($json);


?>

Related JSON Function: json_add()

Other Resources:
http://pretty-print.org/
http://chris.photobooks.com/json/default.htm
https://gist.github.com/906036
http://jsonviewer.stack.hu/
http://www.cerny-online.com/cerny.js/demos/json-pretty-printing

Knowledge Base – It is little use to dig a well after the house has caught fire… SAVE knowledge like Money 😉