-1

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.

axcl
  • 410
  • 6
  • 21
  • `$arr = array( id => 1, msg => "

    Some text

    ")`
    – Blazemonger Nov 01 '16 at 16:42
  • 6
    what do you expect. a json string **MUST** be wrapped in `"`. removing them makes it a json syntax error. changing what json_encode produced is obviously introducing syntax errors. You can NOT redefine what json should be by mangling a json string, then expecting a json parser to accept the bad text you're producing. – Marc B Nov 01 '16 at 16:42
  • 2
    you don't need to do that: `var json = = json_encode($arr); ?>` should be enough. – apokryfos Nov 01 '16 at 16:43
  • Hi @Blazemonger i can not escape double quotes in html because it is already saved in database. – axcl Nov 01 '16 at 16:43
  • 3
    json_encode() will escape double quotes with a backslash and always produces valid JSON. Maybe your decoder is broken? – Gerry Nov 01 '16 at 16:43
  • @Gerry — It's being broken by having the JSON slapped into the middle of a JavaScript string literal without further escaping. – Quentin Nov 01 '16 at 16:46

2 Answers2

6

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.

Daniel W.
  • 31,164
  • 13
  • 93
  • 151
3

When inserting JSON into JavaScript, it is not necessary to wrap it in quotes or even try to parse it, because JSON is a valid JavaScript object or array literal. By removing the quotes, you eliminate the problem of needing to escape quotes.

var json = <?php echo json_encode($arr);?>;
MrCode
  • 63,975
  • 10
  • 90
  • 112