Format JSON with PHP

/**
 * Indents a flat JSON string to make it more human-readable
 *
 * @param string $json The original JSON string to process
 * @return string Indented version of the original JSON string
 */
public static function indent($json) {
 
    $result    = '';
    $pos       = 0;
    $strLen    = strlen($json);
    $indentStr = '  ';
    $newLine   = "\n";
 
    for($i = 0; $i <= $strLen; $i++) {
        
        // Grab the next character in the string
        $char = substr($json, $i, 1);
        
        // If this character is the end of an element, 
        // output a new line and indent the next line
        if($char == '}' || $char == ']') {
            $result .= $newLine;
            $pos --;
            for ($j=0; $j<$pos; $j++) {
                $result .= $indentStr;
            }
        }
        
        // Add the character to the result string
        $result .= $char;
 
        // If the last character was the beginning of an element, 
        // output a new line and indent the next line
        if ($char == ',' || $char == '{' || $char == '[') {
            $result .= $newLine;
            if ($char == '{' || $char == '[') {
                $pos ++;
            }
            for ($j = 0; $j < $pos; $j++) {
                $result .= $indentStr;
            }
        }
    }
 
    return $result;
}



11 Responses to “Format JSON with PHP”  

  1. 1 Resat

    Thank you man. This function very simple & usefull. Now i can easely read server json responses.

  2. 2 dave

    No problem, glad you found it useful!

  3. 3 Jim Higson

    Hi, I found this in Google and made a Smarty (see smarty.net) plugin out of it in about twenty seconds:

    Thanks.

    <?php

    /* Taken from http://recurser.com/articles/2008/03/11/format-json-with-php/ */

    /**
    * Indents a flat JSON string to make it more human-readable
    *
    * param string $json The original JSON string to process
    *
    return string Indented version of the original JSON string
    */
    function smarty_modifier_formatjson($json) {

    $result = ‘’;
    $pos = 0;
    $strLen = strlen($json);
    $indentStr = ‘ ‘;
    $newLine = “\n”;

    for($i = 0; $i <= $strLen; $i ) {

    // Grab the next character in the string
    $char = substr($json, $i, 1);

    // If this character is the end of an element,
    // output a new line and indent the next line
    if($char ‘}’ || $char ‘]’) {
    $result .= $newLine;
    $pos —;
    for ($j=0; $j<$pos; $j ) {
    $result .= $indentStr;
    }
    }

    // Add the character to the result string
    $result .= $char;

    // If the last character was the beginning of an element,
    // output a new line and indent the next line
    if ($char ‘,’ || $char ‘{’ || $char ‘[‘) {
    $result .= $newLine;
    if ($char ‘{’ || $char == ‘[’) {
    $pos ;
    }
    for ($j = 0; $j

  4. 4 Mithun Dhali

    There is an major issue with the code. It does not take into consideration string escaping.

    If a string value (inside quotes) has ‘,’ (COMMA) in it, it simply puts a newline after it. When doing an eval, this will give an unterminated error.

    Example input:
    code”:”“}

    Example output: (Note that in the value html an unwanted newline is added after COMMA.)
    {
    code”,
    success,
    params
    part”,
    entity”,
    html
    }
    }

    The code may work for simple strings, however it will give unexpected errors for complex data in string values.

  5. 5 Yukulélé

    if their is “{[}]” chars in a string eements, theiy ar indented
    exemple :
    indent(‘a{23]”}’);

    {
      “a”:1,
      “b”:”[
        1{
          
        }23
      ]”
    }

  6. 6 Davey Shafik

    This modified version will ignore special characters in quoted strings.

    public static function indent($json) {

    $result = ‘’;
    $pos = 0;
    $strLen = strlen($json);
    $indentStr = ‘ ‘;
    $newLine = “\n”;

    for($i = 0; $i <= $strLen; $i ) {

    // Grab the next character in the string
    $char = substr($json, $i, 1);

    // Skip quoted keys and values
    if ($char '"' || $char "'") {
    echo "Found $char at position $i";
    $lookfor = $char;
    for ($i = $i 1; $i <= $strLen; $i ) {
    $result .= $char;
    $char = substr($json, $i, 1);
    if ($char == $lookfor) {
    echo " and closing $char at $i";
    break;
    }
    }
    }

    // If this character is the end of an element,
    // output a new line and indent the next line
    if($char '}' || $char ']') {
    $result .= $newLine;
    $pos —;
    for ($j=0; $j<$pos; $j ) {
    $result .= $indentStr;
    }
    }

    // Add the character to the result string
    $result .= $char;

    // If the last character was the beginning of an element,
    // output a new line and indent the next line
    if ($char ',' || $char '{' || $char '[') {
    $result .= $newLine;
    if ($char '{' || $char == '[') {
    $pos ;
    }
    for ($j = 0; $j < $pos; $j ) {
    $result .= $indentStr;
    }
    }
    }

    return $result;
    }

  7. 7 Andreas

    Hi Davev,
    your Code from 2009/10/03 produces only errors if I copy/paste it. Could you Post it without all this typing errors? It would be very kind of you.

  8. 8 drapeko

    Thanks for the code, quite useful when you are lazy to do yourself :)

  9. 9 Cybso

    Thanks for this code. I’ve implemented some small enhancements:

    - “$i < $strLen" instead of "$i <= $strLen" – Use $json as an Array instead of using substr – Cache the current $indention for better performance – Check for escaped sequenzes ("Strings") – Parameters $indentStr and $newLine as arguments – Parameter $json as reference

    public static function indentJSON(& $json, $indentStr = “ “, $newLine = “\n”) {
    $result = “”; // Resulting string
    $indention = “”; // Current indention after newline
    $pos = 0; // Indention width
    $escaped = false; // FALSE or escape character
    $strLen = strlen($json);

    for($i = 0; $i < $strLen; $i ) {
    // Grab the next character in the string
    $char = $json[$i];

    if ($escaped) {
    if ($escaped $char) {
    // End of escaped sequence
    $escaped = false;
    }
    $result .= $char;
    if ($char "\" && $i 1 < $strLen) {
    // Next character will NOT end this sequence
    $result .= $json[ $i];
    }
    continue;
    }

    if ($char '"' || $char "'") {
    // Escape this string
    $escaped = $char;
    $result .= $char;
    continue;
    }

    // If this character is the end of an element,
    // output a new line and indent the next line
    if($char '}' || $char ']') {
    $indention = str_repeat($indentStr, —$pos);
    $result .= $newLine . $indention;
    }

    // Add the character to the result string
    $result .= $char;

    // If the last character was the beginning of an element,
    // output a new line and indent the next line
    if ($char ',' || $char '{' || $char '[') {
    if ($char '{' || $char == '[') {
    $indention = str_repeat($indentStr, $pos);
    }
    $result .= $newLine . $indention;
    }
    }

    return $result;
    }

  10. 10 Cybso

    Whoops, seems that some characters got filtered by this comment form. See http://dau-sicher.de/stuff/indentJSON.inc.phps for an unfiltered version.

  1. 1 Ways to Format and View JSON Online - WittySparks


Leave a Reply