Last active
December 24, 2015 05:18
-
-
Save zacscott/6749225 to your computer and use it in GitHub Desktop.
Converts to JSON, in a pretty, human readable format (yet still valid JSON).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Converts to JSON, in a 'pretty', human readable format (yet still | |
* valid JSON). | |
* | |
* This code was modified from this GitHub | |
* <a href="https://gist.github.com/GloryFish/1045396">Gist</a>. | |
* | |
* @param string $json The JSON code to prettify. | |
*/ | |
function prettyJSON($json) { | |
// parser state | |
$tabcount = 0; | |
$result = ''; | |
$inquote = false; | |
$ignorenext = false; | |
// parse JSON, generating the reformatted output | |
for($i = 0; $i < strlen($json); $i++) { | |
$char = $json[$i]; | |
if ($ignorenext) { | |
$result .= $char; | |
$ignorenext = false; | |
// skip parsing of char (in switch below) | |
continue; | |
} | |
switch($char) { | |
case ':': | |
$result .= $char . (!$inquote ? " " : ""); | |
break; | |
case '{': | |
if (!$inquote) { | |
$tabcount++; | |
$result .= "$char\n" . str_repeat("\t", $tabcount); | |
} else { | |
$result .= $char; | |
} | |
break; | |
case '}': | |
if (!$inquote) { | |
$tabcount--; | |
$result = trim($result) . "\n" . str_repeat("\t", $tabcount) . $char; | |
} else { | |
$result .= $char; | |
} | |
break; | |
case ',': | |
if (!$inquote) { | |
$result .= "$char\n" . str_repeat("\t", $tabcount); | |
} else { | |
$result .= $char; | |
} | |
break; | |
case '"': | |
$inquote = !$inquote; | |
$result .= $char; | |
break; | |
case '\\': | |
if ($inquote) $ignorenext = true; | |
$result .= $char; | |
break; | |
default: | |
$result .= $char; | |
} | |
} | |
return $result; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment