Created
June 20, 2017 19:19
-
-
Save dbrent-amazon/ef905b3940d90f1378be0e2e48e40021 to your computer and use it in GitHub Desktop.
phpJsonPrettyPrint
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 | |
function jsonPrettyPrint($request) | |
{ | |
$json = $request["response"]; | |
$result = ''; | |
$level = 0; | |
$in_quotes = false; | |
$in_escape = false; | |
$ends_line_level = null; | |
$json_length = strlen($json); | |
for ($i = 0; $i < $json_length; $i++) { | |
$char = $json[$i]; | |
$new_line_level = null; | |
$post = ""; | |
if ($ends_line_level !== null) { | |
$new_line_level = $ends_line_level; | |
$ends_line_level = null; | |
} | |
if ($in_escape) { | |
$in_escape = false; | |
} elseif ($char === '"') { | |
$in_quotes = !$in_quotes; | |
} elseif (! $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 " ": case "\n": case "\r": | |
$char = ""; | |
$ends_line_level = $new_line_level; | |
$new_line_level = null; | |
break; | |
} | |
} elseif ($char === '\\') { | |
$in_escape = true; | |
} | |
if ($new_line_level !== null) { | |
$result .= "\n".str_repeat(" ", $new_line_level); | |
} | |
$result .= $char.$post; | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment