php json_encode & jquery parseJSON single quote issue

The issue you are facing is that you are presenting the results of the json_encode call to JavaScript as a string whereas it is valid JavaScript. Remove the jQuery.jsonParse set out of the output and simply assign the echoed results to the JavaScript variable in question.

var obj = <?= json_encode(array("casts"=>array(
    "Matthew Modine","Adam Baldwin","Vincent D'Onofrio"
),"year"=>1987)); ?>;

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?>;

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

Tags:

Php

Jquery