Skip to content

Instantly share code, notes, and snippets.

@dbrent-amazon
Created June 20, 2017 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbrent-amazon/ef905b3940d90f1378be0e2e48e40021 to your computer and use it in GitHub Desktop.
Save dbrent-amazon/ef905b3940d90f1378be0e2e48e40021 to your computer and use it in GitHub Desktop.
phpJsonPrettyPrint
<?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