Using Twig to generate JSON

jquery, json, php, twig

Solution

This works for me (twig template):

var parsedJSON = JSON.parse('{{ ['one', 'two', 'three']|json_encode|e('js') }}');

And this:

console.log(parsedJSON);

outputs:

 Array ["one", "two", "three"]

in browser's console.

Problem

I want to have a URL that returns a simple JSON object. I am trying to use Twig to generate the JSON object: ``` { "urls": [ {% for child in page.root %} "{{ child.url }}"{% if not loop.last %},{% endif %} {% endfor %} ] } ``` The carriage returns will not remain in place though, and I keep getting a result that looks like this: ``` {'urls':['../ants/','../brick-report/','../the-pollution-intervention/','../barclay/','../broken-advertising/','../aldat-n-densom/','../thisisart/','../there-she-goes-again/']} ``` which Jquery will not parse with it's ajax or getJSON methods. It's totally ignoring this JSON. How might I convince Twig to put the right whitespace in place? I've looked at the manual and it only seems concerned with NOT inserting whitespace.

Original source