0

我试图在树枝上创建一个 json 对象,所以我需要在循环中设置一个变量。经过多次尝试,我找到了这种方式,但是当我只有两条记录时没关系,如果我还有更多记录,你会产生问题:

{% 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 }}

我想要实现的是:

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

相反,我得到:

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

有没有办法在不发疯的情况下在树枝内构建一个 json 对象?

我已经尝试过这种方式..但重写对象并仅将最后一个元素保存在变量中:

{% 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 }}
4

1 回答 1

1

使用合并

{% 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 }}
于 2013-08-12T05:11:18.540 回答