javascript - JSON.parse 解析“字符串

标签 javascript php json twig

我正在尝试通过这种方式将 JSON 字符串从 PHP Controller 传递到 twig 模板:

$data['dist_result'] = json_encode($distribution_service->setDistribution($ids,$distribution));
$this->display('backend/shipments/distributor_selection.twig', $data);

这是 twig 模板上的 javascript:

{% block javascripts %}
    <script>
        var dist_result = "{{ dist_result }}";
        //var dist_result = dist_result.replace("&quot;","\"");
        console.log(dist_result);
        var data = JSON.parse(dist_result);
        console.log(data);
    </script>
{% endblock %}

无论有没有替换,它都不起作用。

这是 JSON 字符串:

[
  [
    1,
    &quot;Mujer&quot;,
    &quot;18-50&quot;,
    1,
    &quot;Zona1-Noreste&quot;,
    &quot;2&quot;,
    1,
    1,
    1
  ],
  [
    2,
    &quot;Hombre&quot;,
    &quot;18-50&quot;,
    1,
    &quot;Zona1-Noreste&quot;,
    &quot;2&quot;,
    0,
    0,
    2
  ],...

最佳答案

理想情况下,您希望服务器端不对结果进行 html 编码。

但是如果不可能做到这一点,那么一个简单的方法就是让浏览器对其进行解码。

例如..

var txt = `[
  [
    1,
    &quot;Mujer&quot;,
    &quot;18-50&quot;,
    1,
    &quot;Zona1-Noreste&quot;,
    &quot;2&quot;,
    1,
    1,
    1
  ],
  [
    2,
    &quot;Hombre&quot;,
    &quot;18-50&quot;,
    1,
    &quot;Zona1-Noreste&quot;,
    &quot;2&quot;,
    0,
    0,
    2
  ]
]`;

var b = document.createElement("div"); 
b.innerHTML = txt;
var j = JSON.parse(b.innerText);
console.log(j);

关于javascript - JSON.parse 解析“字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58446295/

相关文章:

php - 如何检测标记是否在谷歌地图中的多边形内

php - Yii2 rest api getBodyParams() 无法从 PUT 请求中获取参数

json - Grails-将原始json拆分为一个对象

javascript - 如何设置智能 Morris.js 折线图 y 边界?

javascript - 只有顶部下拉列表正确填充。也需要与其他下拉菜单相同的功能

javascript - 在 Javascript 中实现归并排序

Javascript - 按条件使用链式函数的不同部分

php - Controller 的 Laravel 单元测试

javascript - 如何删除 Bootstrap 轮播

java - Jackson 序列化和反序列化日期时间从/到 WCF 日期时间