Posted By

camdagr8 on 11/05/11


Tagged

php output pretty json


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

wshadow
goliatone


pretty_json


 / Published in: PHP
 

Here's a function to pretty up json encoded data.

  1. function pretty_json($json) {
  2.  
  3. $result = '';
  4. $pos = 0;
  5. $strLen = strlen($json);
  6. $indentStr = ' ';
  7. $newLine = "\n";
  8. $prevChar = '';
  9. $outOfQuotes = true;
  10.  
  11. for ($i=0; $i<=$strLen; $i++) {
  12.  
  13. // Grab the next character in the string.
  14. $char = substr($json, $i, 1);
  15.  
  16. // Are we inside a quoted string?
  17. if ($char == '"' && $prevChar != '\\') {
  18. $outOfQuotes = !$outOfQuotes;
  19.  
  20. // If this character is the end of an element,
  21. // output a new line and indent the next line.
  22. } else if(($char == '}' || $char == ']') && $outOfQuotes) {
  23. $result .= $newLine;
  24. $pos --;
  25. for ($j=0; $j<$pos; $j++) {
  26. $result .= $indentStr;
  27. }
  28. }
  29.  
  30. // Add the character to the result string.
  31. $result .= $char;
  32.  
  33. // If the last character was the beginning of an element,
  34. // output a new line and indent the next line.
  35. if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
  36. $result .= $newLine;
  37. if ($char == '{' || $char == '[') {
  38. $pos ++;
  39. }
  40.  
  41. for ($j = 0; $j < $pos; $j++) {
  42. $result .= $indentStr;
  43. }
  44. }
  45.  
  46. $prevChar = $char;
  47. }
  48.  
  49. return $result;
  50. }

Report this snippet  

You need to login to post a comment.