axcl axcl - 1 month ago 8
PHP Question

Getting rid of ' " ' from json_encode

I have a code snippet that is encoding a PHP array into json but when i am trying to parse it it gives me error because of " present in value

PHP array

$arr = array( id => 1, msg => <h1>Some text</h1> <img src="http://test.png">);


Js code

var json = JSON.parse('<?php echo json_encode($arr);?>');


When i json_encode the above error it surrounds string with double quotes that breaks my JSON.parse function. I tried using replace function but after json_encode it automatically adds double quotes surrounding the string values of object.

So i tried to replace all " with ' but it is replacing all double quotes. i am thinking can it be done by regex to replace only " in html elements or something else. I could not escape HTMl at time of saving because a large number of data is already present in the database and changing it is bit difficult.

Answer

JSON is already parsed the moment PHP does print it.

var json = <?php echo json_encode($arr); ?>;

When do you need JSON.parse() then?

JSON.parse() turns an already escaped JSON into a JSON/Javascript object.

JSON.stringify() does the exact opposite, escaping JSON to a string.