Search code examples
jsontwigpretty-print

Display Twig variable using JSON.stringify


I have a function in a Silex application that executes a cURL statement and returns JSON string which is assigned to the variable curl_result. This variable is then passed into a Twig template like this:

return $twig->render('http.html.twig', ['curl_result' => $result]);

In the Twig template, I am able to display the JSON string variable by using this:

{% if curl_result is defined %}
  <pre>{{ curl_result }}</pre>
{% endif %}

which produces this result:

{"ServiceAccount":[{"Type":"MATTER","ID":[{"body":"1980933400...

Alternatively, when I use JSON_PRETTY_PRINT:

{% if curl_result is defined %}
    <pre>{{ curl_result|json_encode(constant('JSON_PRETTY_PRINT')) }}</pre>
{% endif %}

the only effect seems to be that it places the JSON string within double-quotes, and escapes the inside double-quotes:

"{\"ServiceAccount\":[{\"Type\":\"MATTER\",\"ID\":[{\"body\":\"1980933400...

Neither of these displays the JSON in a usable manner. I want the JSON to be displayed in a human readable format and would like to use JSON.stringify for that purpose. I am able to use the following javascript code and JSON.stringify some random text like this:

<script>
  var jsonString = '{"some":"json"}';
  var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);
  output(jsonPretty);
</script>

If you're still with me after all that, here's my question: How do I bring the Twig variable curl_result into javascript so that I can JSON.stringify it?


Solution

  • In your controller $result is a string, it contains a JSON string but at this point it is only a string. So when you pass it to json_encode it escapes all double quotes because it wants to encode a simple string.

    If you want to use json_encode to pretty print this data, you first need to decode this string (exactly what you did in your alternative solution with JSON.parse), then encode it with pretty print option. So in your controller you should have this change:

    return $twig->render('http.html.twig', ['curl_result' => json_decode($result)]);
    

    You can then use json_encode to pretty print the curl_result in your twig file the exact way you tried in your second twig snippet:

    {% if curl_result is defined %}
        <pre>{{ curl_result|json_encode(constant('JSON_PRETTY_PRINT')) }}</pre>
    {% endif %}
    

    Alternatively, you can print $result as a JS variable in your twig template file like this:

    <script>
          var jsonString = '{{ curl_result | raw }}';
          var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);
          console.log(jsonPretty);
    </script>
    

    Please note the use of raw filter when printing the json string.