简体   繁体   中英

JSON.parse parsing " string

I'm trying to pass a JSON string fron PHP controller to twig template this way:

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

and this is the javascript on the twig template:

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

It doesn't work with replace or without it.

this is thee JSON string:

[
  [
    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
  ],...

Ideally you want the server end to not html encode the result.

But if it's not possible to do this, then a simple approach is let the browser decode it.

eg..

 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);

You can do instead of dist_result.replace("&quot;","\"") that will replace only the first occurrence dist_result.replace(/&quot;/g, '"')

Check more about String.prototype.replace()

Code:

 var dist_result = `[ [ 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 dist_result_replaced = dist_result.replace(/&quot;/g, '"'); var dist_result_parsed = JSON.parse(dist_result_replaced); console.log(dist_result_parsed);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM