0

I noticed that many people are passing objects from PHP to Javascript as JSON like this:

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

or

var obj=jQuery.parseJSON('<?php echo json_encode($obj) ?>');

Why don't people pass JSON directly like this?

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

This works fine with the few objects that I tried. Are there cases when this won't work?

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284
  • You'll generally find the latter mentioned here on SO. http://stackoverflow.com/a/415890, http://stackoverflow.com/a/169035, http://stackoverflow.com/a/14993384 – Jonathan Lonowski Feb 11 '14 at 00:19

2 Answers2

2

passing objects from PHP to Javascript as JSON like this:

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

Ouch! You're right, this is overcomplicated. Also, it actually has serious problems with apostrophes and backslashes in the JSON string, which are not escaped and destroy the string literal.

Why don't people pass JSON directly?

People who do it properly do it this way indeed.

Are there cases when this won't work?

Yes. There are unicode characters that are valid in pure JSON, but a syntax error in JavaScript - see http://timelessrepo.com/json-isnt-a-javascript-subset for details. However, json_encode would output these as escape sequences anyway.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Generally, you'd use JSON parsers to secure situations where the code returned may be erroneous (instead of crashing your script, it will simply throw an exception and keep going). This is generally a good idea when the JSON is sent from a source you don't have control over. It seems unnecessary when you're in control of both ends (PHP server and JS client).

That said, a "safer" method just for server side would be:

<?php $json_encoded = json_encode ($obj); ?>
var obj=<?php echo ($json_encoded ? $json_encoded : 'null'); ?>;

This makes sure only a valid object is passed into JavaScript.

More info: https://api.jquery.com/jQuery.parseJSON/

Tom Murray
  • 99
  • 10