in my project I am using Symfony 4.3 with Twig and javascript with jquery.
I need to pass a json encoded object from php to javascript, but it gets broken with double quotes. For example, on php side I do the following:
$new_obj = new \stdClass;
$new_obj->value = 'Some data with "double " quotes';
print_r(json_encode($new_obj));exit;
return $this->render('mytemplate.html.twig', [
'new_obj' => $new_obj
]);
So here print_r(json_encode($new_obj))
gives the following:
{"value":"Some data with \"double \" quotes"}
and this looks loke valid json because double qoutes get escaped with slashes. But when I get it in my twig
template, I receive the following:
{"value":"Some data with "double " quotes"}
So double quotes are replaced with "
and escaping slash gets removed at all. I can restore encoded quotes back with the following code:
function htmlDecode(input){
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
but how can I make my json valid again? JSON.parse()
says
Uncaught SyntaxError: Unexpected token d in JSON at position 26
at JSON.parse (<anonymous>)
[![pic][1]][1]
and I have alreadt tried twig internal {{ data|json_encode() }}
function on my raw object, or json_encode($new_obj, JSON_HEX_QUOT)
but it did not help.
Any ideas how to fix it would be welcome. Thank you.