sepehr
6/23/2014 - 9:40 AM

PHP: JSON prettyprint helper

PHP: JSON prettyprint helper

<?php

/**
 * Pretty print JSON objects.
 *     
 * @param  array $json JSON array to be printed.
 * 
 * @return string
 */
function json_prettyprint($json)
{
    if (defined("JSON_PRETTY_PRINT"))
    {
        return json_encode($json, JSON_PRETTY_PRINT);
    }

    // Array passed?
    if (is_array($json))
    {
    	$json = json_encode($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++)
    {
        $post           = "";
        $new_line_level = NULL;
        $char           = $json[$i];

        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;
            } // switch
        } // if

        else if ($char === '\\')
        {
            $in_escape = TRUE;
        }

        if ($new_line_level !== NULL)
        {
            $result .= "\n" . str_repeat("\t", $new_line_level);
        }

        $result .= $char . $post;
    }

    return $result;
}