Search code examples
phpjsonsmarty

Pretty print json object in smarty


How can I pretty print into a div a json string assigned to smarty?

i know i can run php functions in smarty, so maybe a custom function will work?

thanks in advance.


Solution

  • The easiest thing to do is to convert the object to an associative array, and then parse it. The function would look like this:

    function format_json($array, $indent) {
    
        $indent_text = '';
    
        for ($ii = 0;$ii < $indent; $ii++)
            $indent_text .= '    ';
    
        echo '<br />'.$indent_text.'{<br />';
    
        foreach ($array as $key => $value) {
            echo $indent_text.'"'.$key.'" : '; 
            if (is_array($value))
                format_json( $value, $indent + 1 );
            else echo '"'.$value.'"; <br />';
        }
        echo $indent_text.'}<br />';
    }
    
    <pre><code><?php format_json(json_decode($your_json_object, true), 0); ?></code></pre>
    

    Obviously, you can style the tag and change the indentation any way you want.