Code snippets, tech tricks and other bits and bobs

Output human-readable JSON with PHP

Working with the Zencoder API I wanted to check my JSON before attempting to submit it – easy enough to output, but to read?

To the Google! Turns up trumps with http://www.webdeveloper.com/forum/showthread.php?t=235140 where user janusmcarthy has provided this nifty little function. Pretty much the way I’d have done it, but didn’t want to spend the time writing.

strip_html_tags() Function

function jsonToReadable( $jsonString)
{
    $tabcount = 0;
    $result = '';
    $inquote = false;

    $tab = "   ";
    $newline = "\n";

    for($i = 0; $i < strlen( $jsonString); $i++) 
    {
            $char = $jsonString[ $i];

            if( $char == '"' && $jsonString[ $i-1] != '\\') $inquote = !$inquote;

            if( $inquote)
            {
                $result.=$char;
                continue;
            }

            switch($char) 
            {
                case '{':
                        if( $i) $result.=$newline;
                        $result.=str_repeat($tab, $tabcount).$char.$newline.str_repeat( $tab, ++$tabcount);
                        break;
                case '}':
                        $result.=$newline.str_repeat( $tab, --$tabcount).$char;
                        break;
                case ',':
                        $result.=$char;
                        if( $jsonString[ $i+1] != '{') $result.=$newline.str_repeat($tab, $tabcount);
                        break;
                default:
                        $result.=$char;
            }
    }
    return $result;
}

Filed under  //   JSON   PHP