views:

8586

answers:

4

A double quote even if escaped is throwing parse error.
look at the code below

//parse the json in javascript  
var testJson = '{"result": ["lunch", "\"Show\""] }';  
var tags = JSON.parse(testJson);  
alert (tags.result[1]);

This is throwing parse error because of the double quotes (which are already escaped).
Even eval() won't work here.
But if i escape it with double slashes like this:

var result = '{"result": ["lunch", "\\"Show\\""] }';  
var tags = JSON.parse(result);  
alert (tags.result[1]);

then it works fine.
Why do we need to use double slash here in javascript? The problem is that PHP json_encode() function escapes a double quote with a single slash (like this: \"show\") which JSON.parse won't be able to parse. How do i handle this situation?

+4  A: 

Javascript unescapes its strings and json unescapes them as well. the first string ( '{"result": ["lunch", "\"Show\""] }' ) is seen by the json parser as {"result": ["lunch", ""Show""] }, because \" in javascript means ", but doesn't exit the double quoted string.

The second string '{"result": ["lunch", "\\\"Show\\\""] }' gets first unescaped to {"result": ["lunch", "\"Show\""] } (and that is correctly unescaped by json).

I think, that '{"result": ["lunch", "\\"Show\\""] }' should work too.

cube
+1  A: 

From the docs

JSON_HEX_APOS (integer) All ' are converted to \u0027
JSON_HEX_QUOT (integer) All " are converted to \u0022

json_encode() takes two args, the value and options. So try

json_encode($result, JSON_HEX_QUOT); // or
json_encode($result, JSON_HEX_QUOT | JSON_HEX_APOS);

I haven't tried this though.

Ólafur Waage
+5  A: 

Well, finally, JSON's parse uses the same eval, so there's no difference when you give them smth. with incorrect syntax. In this case you have to escape correctly your quotes in php, and then escape them and their escaping slashes with json_encode

<?php
    $json = '{"result": ["lunch", "\"Show\""] }';
    echo json_encode($json);
?>

OUTPUT: "{\"result\": [\"lunch\", \"\\\"Show\\\"\"] }"

This should work on client-side JS (if I've made no typos).

Jet
But this is something which should be taken care of by the json_encode() function.Why is it returning something which can not be correctly parsed by JSON.parse().
Varun
Does this mean php_encode() is buggy ..??
Varun
It's not a bug in json_encode (I'm assuming that's what you meant). json_encode is not intended to create JavaScript string literals, so it doesn't do the additional escaping.
Matthew Crumley
Right. That's what I mean.
Jet
A: 

turn off magic_quotes_gpc in php.ini

theo