将数据从PHP转换为JSON数组

时间:2018-11-20 15:27:21

标签: javascript jquery json twig

我需要一些数据,这些数据需要从Twig PHP模板引擎中检索并转换为JS JSON数组。

我能够遍历TWIG中的PHP数组并将值推入JS,如下所示:

  var results = []
  {% for res in pqRes|reverse %}
        var res =  "{" + "{{res|raw}}" + "}"
        results.push(res)
  {% endfor %}

这会在我console.log结果时创建如下数组

 0: "{value: 1, meta: 'Meets'}"
 1: "{value: 2, meta: 'Exceeds'}"
 2: "{value: 1, meta: 'Meets'}"
 3: "{value: 1, meta: 'Meets'}"
 4: "{value: 0, meta: 'Fails'}"

如何将这些值推入JSON数组中,以便每个项目都没有引号?

最终,我需要将值推入如下所示的数据结构中:

var chart = new Chartist.Line('.ct-chart', {
 labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
 series: [{
  name: 'Workload',
  meta: {customData: 123},
  data: [
      {value: 1, meta: 'This can be anything and will be serialized'},
      {value: 4, meta: {text: 'Can even be Objects'}},
      {value: 2, meta: 10000},
      {value: 1, meta: 'This can be anything and will be serialized'},
      {value: 2, meta: 'This can be anything and will be serialized'}
 ]
 }]
}
});

来源(https://jsbin.com/kivole/1/edit?js,output

1 个答案:

答案 0 :(得分:0)

此时,您只是将字符串推入javascript数组中。不要使用数组...

var obj = { {% for string in foo %}{{ string | raw }},{% endfor %} };

demo