Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php json_encode & jquery parseJSON single quote issue

Tags:

jquery

php

I searched and read most of the related topics, but they weren't what I was looking for.

I've a JSON enocded string with json_encode PHP function:

{"casts":["Matthew Modine","Adam Baldwin","Vincent D'Onofrio"],"year":1987} 

I'm working with jQuery to put the values in appropriate fields too, in the case of testing I did the below:

<script> var obj = jQuery.parseJSON('<?=$data?>'); console.log(obj); </script> 

Suppose that $data is this:

$data = <<<END {"casts":["Matthew Modine","Adam Baldwin","Vincent D'Onofrio"],"year":1987} END; 

What Google chrome console produces in this case:

Uncaught SyntaxError: Unexpected identifier  

However when I make a change in JSON encoded string - adding Backslash to single quote :

{"casts":["Matthew Modine","Adam Baldwin","Vincent D\'Onofrio"],"year":1987} 

Console output is as normal:

Object {casts: Array[3], year: 1987} casts: Array[3] year: 1987 

The question: is this error in console expected? I think escaping or replacing ' with \' will be so dirty!

UPDATED

Actually $data value comes from a json_encode($var) and $var is an array!

$data = json_encode($var); 
like image 698
revo Avatar asked Jul 29 '13 14:07

revo


2 Answers

For the broader problem of passing a JSON-encoded string in PHP (e.g., through cURL), using the JSON_HEX_APOS option is the cleanest way to solve this problem. This would solve your problem as well, although the previous answers are correct that you don't need to call parseJSON, and the JavaScript object is the same without calling parseJSON on $data.

For your code, you would just make this change:

json_encode($var) to json_encode($var, JSON_HEX_APOS).

Here's an example of the correctly encoded data being parsed by jQuery: http://jsfiddle.net/SuttX/

For further reading, here's an example from the PHP.net json_encode manual entry Example #2:

$a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9");  echo "Apos: ",    json_encode($a, JSON_HEX_APOS), "\n"; 

This will output:

Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"] 

A full list of JSON constants can be found here: PHP.net JSON constants

like image 172
seanvalencourt Avatar answered Oct 11 '22 09:10

seanvalencourt


However when I make a change in JSON encoded string - adding Backslash to single quote

That escapes it in the PHP string literal. It is then inserted into the PHP string as a simple '.

If you want to escape it before inserting it into JavaScript then you need to add slashes to the string you get out of json_encode (or rather, since you aren't using that (you should be!) the JSON string you build by hand).

That is more work then you need though. The real solution is to remember that JSON is a subset of JavaScript literal syntax:

var obj = <?=$data?>; 
like image 44
Quentin Avatar answered Oct 11 '22 08:10

Quentin