Skip to content

Instantly share code, notes, and snippets.

@1905
Created September 25, 2011 10:31
Show Gist options
  • Save 1905/1240460 to your computer and use it in GitHub Desktop.
Save 1905/1240460 to your computer and use it in GitHub Desktop.
human readable json_encode output
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment