nathan15

Indent JSON

Mar 10th, 2013
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.62 KB | None | 0 0
  1. /**
  2.  * Indents a flat JSON string to make it more human-readable.
  3.  *
  4.  * @param string $json The original JSON string to process.
  5.  *
  6.  * @return string Indented version of the original JSON string.
  7.  */
  8. function indent($json) {
  9.  
  10.     $result      = '';
  11.     $pos         = 0;
  12.     $strLen      = strlen($json);
  13.     $indentStr   = '  ';
  14.     $newLine     = "\n";
  15.     $prevChar    = '';
  16.     $outOfQuotes = true;
  17.  
  18.     for ($i=0; $i<=$strLen; $i++) {
  19.  
  20.         // Grab the next character in the string.
  21.         $char = substr($json, $i, 1);
  22.  
  23.         // Are we inside a quoted string?
  24.         if ($char == '"' && $prevChar != '\\') {
  25.             $outOfQuotes = !$outOfQuotes;
  26.        
  27.         // If this character is the end of an element,
  28.         // output a new line and indent the next line.
  29.         } else if(($char == '}' || $char == ']') && $outOfQuotes) {
  30.             $result .= $newLine;
  31.             $pos --;
  32.             for ($j=0; $j<$pos; $j++) {
  33.                 $result .= $indentStr;
  34.             }
  35.         }
  36.        
  37.         // Add the character to the result string.
  38.         $result .= $char;
  39.  
  40.         // If the last character was the beginning of an element,
  41.         // output a new line and indent the next line.
  42.         if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
  43.             $result .= $newLine;
  44.             if ($char == '{' || $char == '[') {
  45.                 $pos ++;
  46.             }
  47.            
  48.             for ($j = 0; $j < $pos; $j++) {
  49.                 $result .= $indentStr;
  50.             }
  51.         }
  52.        
  53.         $prevChar = $char;
  54.     }
  55.  
  56.     return $result;
  57. }
Add Comment
Please, Sign In to add comment