猿问

JSON.parse 解析 细绳

我正在尝试通过这种方式将来自 PHP 控制器的 JSON 字符串传递给树枝模板:


$data['dist_result'] = json_encode($distribution_service->setDistribution($ids,$distribution));

$this->display('backend/shipments/distributor_selection.twig', $data);

这是树枝模板上的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

  ],...


Helenr
浏览 135回答 2
2回答

杨__羊羊

理想情况下,您希望服务器端不对结果进行 html 编码。但是,如果无法做到这一点,那么一个简单的方法就是让浏览器对其进行解码。例如..var txt = `[&nbsp; [&nbsp; &nbsp; 1,&nbsp; &nbsp; &quot;Mujer&quot;,&nbsp; &nbsp; &quot;18-50&quot;,&nbsp; &nbsp; 1,&nbsp; &nbsp; &quot;Zona1-Noreste&quot;,&nbsp; &nbsp; &quot;2&quot;,&nbsp; &nbsp; 1,&nbsp; &nbsp; 1,&nbsp; &nbsp; 1&nbsp; ],&nbsp; [&nbsp; &nbsp; 2,&nbsp; &nbsp; &quot;Hombre&quot;,&nbsp; &nbsp; &quot;18-50&quot;,&nbsp; &nbsp; 1,&nbsp; &nbsp; &quot;Zona1-Noreste&quot;,&nbsp; &nbsp; &quot;2&quot;,&nbsp; &nbsp; 0,&nbsp; &nbsp; 0,&nbsp; &nbsp; 2&nbsp; ]]`;var b = document.createElement("div");&nbsp;b.innerHTML = txt;var j = JSON.parse(b.innerText);console.log(j);

沧海一幻觉

你可以做而不是dist_result.replace("&quot;","\"")只替换第一次出现dist_result.replace(/&quot;/g, '"')查看更多关于String.prototype.replace()代码:var dist_result = `[&nbsp; [&nbsp; &nbsp; 1,&nbsp; &nbsp; &quot;Mujer&quot;,&nbsp; &nbsp; &quot;18-50&quot;,&nbsp; &nbsp; 1,&nbsp; &nbsp; &quot;Zona1-Noreste&quot;,&nbsp; &nbsp; &quot;2&quot;,&nbsp; &nbsp; 1,&nbsp; &nbsp; 1,&nbsp; &nbsp; 1&nbsp; ],&nbsp; [&nbsp; &nbsp; 2,&nbsp; &nbsp; &quot;Hombre&quot;,&nbsp; &nbsp; &quot;18-50&quot;,&nbsp; &nbsp; 1,&nbsp; &nbsp; &quot;Zona1-Noreste&quot;,&nbsp; &nbsp; &quot;2&quot;,&nbsp; &nbsp; 0,&nbsp; &nbsp; 0,&nbsp; &nbsp; 2&nbsp; ]]`;var dist_result_replaced = dist_result.replace(/&quot;/g, '"');var dist_result_parsed = JSON.parse(dist_result_replaced);console.log(dist_result_parsed);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答