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;
}



4 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.

Leave a Reply