Prettify json by using a new tag "format_json". Json can be passed as string or as variable, with parameter or without

Code: Select all
<cms:set my_json='{ "city" : "London" }' is_json='1' />

<pre><cms:json_format json='{ "city" : "London" }' /></pre>
<pre><cms:json_format json=my_json /></pre>

<pre><cms:json_format '{ "city" : "London" }' /></pre>
<pre><cms:json_format my_json /></pre>


Result:
Code: Select all
{
  "city":"London"
}


Code to paste in couch/addons/kfunctions.php:
Code: Select all

// cms:json_format tag
// <cms:json_format myvar />
$FUNCS->register_tag( 'json_format', 'tag_json_format' );
function tag_json_format( $params, $node ){
    global $CTX, $FUNCS;
   
    if( count($node->children) ) {die("ERROR: Tag \"".$node->name."\" is a self closing tag");}
   
    $value = $params[0]['rhs'];
    $json = is_array( $value ) ? $FUNCS->json_encode( $value ) : $value;
   
    $result       = '';
    $pos          = 0;
    $strLen       = strlen($json);
    $indentStr    = '  ';
    $newLine      = "\n";
    $prevChar     = '';
    $prevPrevChar = '';
    $outOfQuotes  = true;

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

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

        // Are we inside a quoted string?
        // The next character is only escaped if the previous was "\" and the one before wasn't "\".
        $escaped = $prevChar == '\\' && $prevPrevChar != '\\';
        if ($char == '"' && !$escaped) {
            $outOfQuotes = !$outOfQuotes;

            // If this character is the end of an element,
            // output a new line and indent the next line.
        } else {
            if (($char == '}' || $char == ']') && $outOfQuotes) {
                if (substr($json, $i - 1, 1) !== '[') {
                    $result .= $newLine;
                }
                $pos--;
                if (substr($json, $i - 1, 1) !== '[') {
                    $result .= str_repeat($indentStr, $pos);
                }
            }
        }

        // 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 == '[') && $outOfQuotes) {
            if (substr($json, $i + 1, 1) !== ']') {
                $result .= $newLine;
            }
            if ($char == '{' || $char == '[') {
                $pos++;
            }

            if (substr($json, $i + 1, 1) !== ']') {
                $result .= str_repeat($indentStr, $pos);
            }
        }

        $prevPrevChar = $prevChar;
        $prevChar     = $char;
    }

    return $result; 
   
}