. . . Someone asked me this question. . I'm not too sure either
JSON.parse(`{
"test": "这是一个对象, 里面有 test 字段"
}`)
The above can run normally. . The result is {test: "This is an object with a test field"}
But if you add double quotes
to the test
field, there will be a very strange problem..
JSON.parse(`{
"test": "这是一个对象, 里面有 "test" 字段"
}`)
The above will report an error. This is normal.
Now add escape character
JSON.parse(`{
"test": "这是一个对象, 里面有 \"test\" 字段"
}`)
The result is still an error, even if I input this string directly, the escaped string can be displayed normally, as shown in the figure:
The amazing thing is. . I accidentally wrote code like this, using \\
as the escape character instead of \
. . . The result is normal.
It should be because the execution process of JSON.parse actually undergoes two escapes.
Once is the escape of the string itself:
is converted to
(You can enter this string directly on the command line of the browser)
Once is the escape when converting string to object:
Because it has been converted to
"" will be considered as the escape character of """ and will be correctly converted into an object.
When there is only one "", when the string is converted to an object, there are two pairs of double quotes in the test field value, and an error will be reported.
I checked the parse method in the ES5 specification again:
The first step should be to escape the corresponding string itself
The second step corresponds to the escaping when converting string to object