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(""","\"");
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,
"Mujer",
"18-50",
1,
"Zona1-Noreste",
"2",
1,
1,
1
],
[
2,
"Hombre",
"18-50",
1,
"Zona1-Noreste",
"2",
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, "Mujer", "18-50", 1, "Zona1-Noreste", "2", 1, 1, 1 ], [ 2, "Hombre", "18-50", 1, "Zona1-Noreste", "2", 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(""","\"")
that will replace only the first occurrence dist_result.replace(/"/g, '"')
Check more about String.prototype.replace()
Code:
var dist_result = `[ [ 1, "Mujer", "18-50", 1, "Zona1-Noreste", "2", 1, 1, 1 ], [ 2, "Hombre", "18-50", 1, "Zona1-Noreste", "2", 0, 0, 2 ] ]`; var dist_result_replaced = dist_result.replace(/"/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.