0

I'm trying to create a json object on twig, so I need to set a variable inside a loop. After many attempts I found this way, but it's fine when I only have two records, if I have any more you generate the problem:

{% set data = [] %}
{% for artist in artists %}
     {% if loop.first %}
         {%
         set data = {
               id        : artist.id,
               text      : artist.name|capitalize() ~' '~ artist.surname|capitalize()
             }
         %}
     {% else %}
         {%
          set data = [data,{
              id        : artist.id,
              text      : artist.name|capitalize() ~' '~ artist.surname|capitalize()
            }]
         %}
     {% endif %}
 {% endfor %}
 {% set data = {results: data} %}
 {{ data|json_encode|raw }}

What I want to achieve is:

{results: [{id: 1, text: "bla"},{id: 2, text: "blabla"},{id: 3, text: "blablabla"}]}

Instead I get:

{results:[[{id:1,text:"bla"},{id:2,text:"blabla"}],{id:3,text:"blablabla"}]}

Is there a way to build a json object inside twig without going crazy?

I've already tried this way .. but rewrites the object and saves in the variable only the last element:

{% set data = [] %}
{% for artist in artists %}
     {%
      set data = {
          id        : artist.id,
          text      : artist.name|capitalize() ~' '~ artist.surname|capitalize()
        }
     %}
{% endfor %}
{% set data = {results: data} %}
{{ data|json_encode|raw }}

1 Answer 1

1

Use merge.

{% set data = [] %}
{% for artist in artists %}
     {%
      set data = data|merge ([{
          id        : artist.id,
          text      : artist.name|capitalize() ~' '~ artist.surname|capitalize()
        }])
     %}
{% endfor %}
{% set data = {results: data} %}
{{ data|json_encode|raw }}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! Working up at 5 am makes bad jokes!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.