Home » Php » php – Using Twig to generate JSON

php – Using Twig to generate JSON

Posted by: admin July 12, 2020 Leave a comment


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:


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.

How to&Answers:

That works for me (twig template):

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

And that:


will output:

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

in FF console.


Twig has a filter for this.

json_encode, it uses PHP json_encode function.

for your case:

{{ {'urls': page.root}|json_encode }}

will output


the code is tested and works. For more information take a look at the Twig Documentation for json_encode.


Don’t use Twig to generate your json response.

In your controller, use:

return new Response(json_encode($var));


public function sampleAction()
    $urls = array('../test', '../something', '../sample');
    return new Response(json_encode($var));

If URLs are generated from Symfony2 routes, you can use:

public function sampleAction()
    $urls = array(
    return new Response(json_encode($var));


Thats easy if you extend twig.

First, create a class that will contain the extension:


namespace Acme\DemoBundle\Twig\Extension;

use Symfony\Component\DependencyInjection\ContainerInterface;  
use \Twig_Extension;

class VarsExtension extends Twig_Extension
    protected $container;

    public function __construct(ContainerInterface $container) 
        $this->container = $container;

    public function getName() 
        return 'some.extension';

    public function getFilters() {
        return array(
            'json_decode'   => new \Twig_Filter_Method($this, 'jsonDecode'),

    public function jsonDecode($str) {
        return json_decode($str);


Try wrapping your template in an autoescape block:

{% autoescape 'js' %}
  { "href": "{{ my_url }}" }
{% endautoescape%}


Basically the $.getJson() method requires json but ther is a string
so you can use $.get() to get the response and use the parser to parse the string to JSON

 // user parser