Coded something up in Couch in an interesting way? Have a snippet or shortcode to share? Post it here for the community to benefit.
2 posts Page 1 of 1
Prettify json by using a new tag.

Code: Select all
<cms:set my_json='{"Russia":{"Moscow":"cold","Sochi":"warm"}"India":{"Mumbai":"pleasant","Delhi":"moderate"},"Miami":"great","Utopia":["unknown","uncertain","finicky"]}' is_json='1' />

<cms:print_json json=my_json html='1' />


Result:
Code: Select all
{
    "Russia":{
        "Moscow":"cold",
        "Sochi":"warm"
    },
    "India":{
        "Mumbai":"pleasant",
        "Delhi":"moderate"
    },
    "Miami":"great",
    "Utopia":[
        "unknown",
        "uncertain",
        "finicky"
    ]
}


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


$FUNCS->register_tag( 'print_json', 'tag_json_format' );
// cms:print_json tag
// https://www.couchcms.com/forum/viewtopic.php?f=8&t=11466
// Example 1: <cms:print_json json=my_json />
// Example 2: <cms:print_json json="<cms:show my_json as_json='1' />" />
// Example 3: <cms:print_json json='{ "city" : "London" }' />
// Example 4: <cms:print_json my_json html='1' />
function tag_json_format( $params, $node ){
    global $CTX, $FUNCS;
   
    if( count($node->children) ) {die("ERROR: Tag \"".$node->name."\" is a self closing tag");}

    extract( $FUNCS->get_named_vars(
                array(
                      'json'=>'',    // json input into $json
                      'var'=>'',     // syn: $json
                      'html'=>'0',   // wrap json in html-markup for browser view
                    ),
                $params)
           );

   if( $json!=='' && is_array($json) ) $json = json_encode($json);
   if( $var!==''  && is_array($var) )    $var  = json_encode($var);
   
   // make sure we have json at hands
   if ( $json!=='' || $var!=='' ){ $json = $json . $var; } else { return; };
   
    $result       = '';
    $pos          = 0;
    $strLen       = strlen($json);
    $indentStr    = ( $html == '1' ) ? '&nbsp;&nbsp;&nbsp;&nbsp;' : '  ';
    $newLine      = ( $html == '1' ) ? "<br/>"  : "\r\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; 
   
}

Tag updated. Now fine-prints in browser if parameter html is set to '1'. Much easier to copy-paste good-looking json.
2 posts Page 1 of 1

Who is online

In total there are 3 users online :: 0 registered, 0 hidden and 3 guests
(based on users active over the past 5 minutes)

Users browsing this forum: No registered users and 3 guests