使用双引号的json解析错误

时间:2022-09-15 13:11:21

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:

这是由于双引号(已经转义)而导致的解析错误。即使eval()也不能在这里工作。但如果我用这样的双斜杠来逃避它:

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?

然后它将正常工作。为什么我们需要在javascript中使用双斜杠?问题是PHP json_encode()函数用一个斜杠(如:\“show\”)转义一个双引号(JSON)。解析无法解析。我该如何处理这种情况?

7 个解决方案

#1


30  

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

最后,JSON的解析使用相同的eval,所以给它们smth没有区别。不正确的语法。在这种情况下,您必须正确地转义php中的引号,然后使用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).

这应该适用于客户端JS(如果我没有输入错误的话)。

#2


34  

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.

Javascript不转义字符串,json也不转义字符串。第一个字符串('{"result": ["lunch", "\"Show\"]})被json解析器视为{"result": ["lunch", "Show"]},因为"\"在javascript中的意思是",但不退出双引号字符串。

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

第二个字符串{"result": ["lunch", "\\\"Show\\ "\" \"]}'首先未转义到{"result": ["lunch", "\"Show\"]}(这是json正确的未转义)。

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

我认为,“{“结果”:[“午餐”,“\ \”显示\ \ "]}”也应该工作。

#3


11  

This problem is caused by the two-folded string escaping mechanism: one comes from JS and one comes from JSON.

这个问题是由双折字符串转义机制引起的:一个来自JS,一个来自JSON。

A combination of the backslash character combined with another following character is used to represent one character that is not otherwise representable within the string. ''\\'' stands for '\' etc.

反斜杠字符与后面的另一个字符的组合用于表示字符串中不能表示的一个字符。“\\”代表“\”等。

This escaping mechanism takes place before JSON.parse() works.

这种转义机制发生在JSON.parse()工作之前。

For Example,

例如,

var parsedObj = JSON.parse('{"sentence": "It is one backslash(\\\\)"}');
console.log(parsedObj.sentence);
>>>"It is one backslash(\)"

From the string generator's perspective, it passes four backlashes '\' into the JavaScript interpretor.

从字符串生成器的角度来看,它向JavaScript解释器传递4个反斜杠“\”。

From the JavaScript interpretor's perspective, it inteprets there are two backlashes(\) as each '\\' sequence will be interpreted as one '\'.

从JavaScript解释器的角度来看,它有两个反斜杠(\),因为每个“\”序列将被解释为一个“\”。

From the JSON parser's perspective, it receives two backlashes(\\) and the JSON string escape rules will parses it as one single '\' which is the output result.

从JSON解析器的角度来看,它接收到两个回睫毛(\\),JSON字符串转义规则将把它解析为一个“\”,这是输出结果。

Explain you first code:

解释你第一次代码:

var testJson = '{"result": ["lunch", "\"Show\""] }';
//The real string after sequence escaping in to JS is
//'{"result": ["lunch", ""Show""] }' 
//which is passed into the JSON.parse.
//Thus, it breaks the JSON grammar and generates an error
var tags = JSON.parse(testJson);  
alert (tags.result[1]);

#4


9  

From the docs

从文档

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

JSON_HEX_APOS (integer)被转换为\u0027 JSON_HEX_QUOT (integer)被转换为\u0022

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

json_encode()使用两个args,值和选项。所以尝试

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

I haven't tried this though.

我还没试过。

#5


3  

Turn off magic_quotes_gpc in php.ini.

在php.ini中关闭magic_quotes_gpc。

#6


2  

php to javascript Object (php >= 5.3.0)

var storesLocations = JSON.parse('<?php echo addslashes(json_encode($storesLocations,JSON_HEX_APOS | JSON_HEX_QUOT)) ?>');

#7


0  

If the standard C escapes are added, then JSON.parse will convert sequences like \" into ", \\ into \, \n into a line-feed, etc.

如果添加了标准的C转义,则添加JSON。parse将把像“\”这样的序列转换成“\”、“\”转换成“\”、“\n”转换成“行提要”等等。

'foo\\bar\nbaz"' === JSON.parse('"foo\\\\bar\\nbaz\\""')

In our project's case:

在我们项目的情况:

original string ""{\"lat\":28.4594965,\"lng\":77.0266383}""

原始字符串" " { \“lat \”:28.4594965,\“液化天然气\”:77.0266383 } "

After passing to JSON.parse()

经过JSON.parse()

"{"lat":28.4594965,"lng":77.0266383}"

On 2nd pass to JSON.parse()

第2次传递到JSON.parse()

{lat: 28.4594965, lng: 77.0266383}

Notice that JSON.parse() removed escaping characters instead of converting string to object.

注意,JSON.parse()删除了转义字符,而不是将字符串转换为对象。

After the escaping characters were removed, the string to object conversion worked.

在删除转义字符之后,从字符串到对象的转换工作了。

Here is the demo:

这是演示:

while (typeof p1 != 'object') {
  p1 = JSON.parse(p1);
  pass++;
  console.log('On pass ', pass, p1);
}

#1


30  

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

最后,JSON的解析使用相同的eval,所以给它们smth没有区别。不正确的语法。在这种情况下,您必须正确地转义php中的引号,然后使用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).

这应该适用于客户端JS(如果我没有输入错误的话)。

#2


34  

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.

Javascript不转义字符串,json也不转义字符串。第一个字符串('{"result": ["lunch", "\"Show\"]})被json解析器视为{"result": ["lunch", "Show"]},因为"\"在javascript中的意思是",但不退出双引号字符串。

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

第二个字符串{"result": ["lunch", "\\\"Show\\ "\" \"]}'首先未转义到{"result": ["lunch", "\"Show\"]}(这是json正确的未转义)。

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

我认为,“{“结果”:[“午餐”,“\ \”显示\ \ "]}”也应该工作。

#3


11  

This problem is caused by the two-folded string escaping mechanism: one comes from JS and one comes from JSON.

这个问题是由双折字符串转义机制引起的:一个来自JS,一个来自JSON。

A combination of the backslash character combined with another following character is used to represent one character that is not otherwise representable within the string. ''\\'' stands for '\' etc.

反斜杠字符与后面的另一个字符的组合用于表示字符串中不能表示的一个字符。“\\”代表“\”等。

This escaping mechanism takes place before JSON.parse() works.

这种转义机制发生在JSON.parse()工作之前。

For Example,

例如,

var parsedObj = JSON.parse('{"sentence": "It is one backslash(\\\\)"}');
console.log(parsedObj.sentence);
>>>"It is one backslash(\)"

From the string generator's perspective, it passes four backlashes '\' into the JavaScript interpretor.

从字符串生成器的角度来看,它向JavaScript解释器传递4个反斜杠“\”。

From the JavaScript interpretor's perspective, it inteprets there are two backlashes(\) as each '\\' sequence will be interpreted as one '\'.

从JavaScript解释器的角度来看,它有两个反斜杠(\),因为每个“\”序列将被解释为一个“\”。

From the JSON parser's perspective, it receives two backlashes(\\) and the JSON string escape rules will parses it as one single '\' which is the output result.

从JSON解析器的角度来看,它接收到两个回睫毛(\\),JSON字符串转义规则将把它解析为一个“\”,这是输出结果。

Explain you first code:

解释你第一次代码:

var testJson = '{"result": ["lunch", "\"Show\""] }';
//The real string after sequence escaping in to JS is
//'{"result": ["lunch", ""Show""] }' 
//which is passed into the JSON.parse.
//Thus, it breaks the JSON grammar and generates an error
var tags = JSON.parse(testJson);  
alert (tags.result[1]);

#4


9  

From the docs

从文档

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

JSON_HEX_APOS (integer)被转换为\u0027 JSON_HEX_QUOT (integer)被转换为\u0022

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

json_encode()使用两个args,值和选项。所以尝试

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

I haven't tried this though.

我还没试过。

#5


3  

Turn off magic_quotes_gpc in php.ini.

在php.ini中关闭magic_quotes_gpc。

#6


2  

php to javascript Object (php >= 5.3.0)

var storesLocations = JSON.parse('<?php echo addslashes(json_encode($storesLocations,JSON_HEX_APOS | JSON_HEX_QUOT)) ?>');

#7


0  

If the standard C escapes are added, then JSON.parse will convert sequences like \" into ", \\ into \, \n into a line-feed, etc.

如果添加了标准的C转义,则添加JSON。parse将把像“\”这样的序列转换成“\”、“\”转换成“\”、“\n”转换成“行提要”等等。

'foo\\bar\nbaz"' === JSON.parse('"foo\\\\bar\\nbaz\\""')

In our project's case:

在我们项目的情况:

original string ""{\"lat\":28.4594965,\"lng\":77.0266383}""

原始字符串" " { \“lat \”:28.4594965,\“液化天然气\”:77.0266383 } "

After passing to JSON.parse()

经过JSON.parse()

"{"lat":28.4594965,"lng":77.0266383}"

On 2nd pass to JSON.parse()

第2次传递到JSON.parse()

{lat: 28.4594965, lng: 77.0266383}

Notice that JSON.parse() removed escaping characters instead of converting string to object.

注意,JSON.parse()删除了转义字符,而不是将字符串转换为对象。

After the escaping characters were removed, the string to object conversion worked.

在删除转义字符之后,从字符串到对象的转换工作了。

Here is the demo:

这是演示:

while (typeof p1 != 'object') {
  p1 = JSON.parse(p1);
  pass++;
  console.log('On pass ', pass, p1);
}