javascript - How to understand escape characters in JSON.parse()?
世界只因有你
世界只因有你 2017-06-14 10:51:54
0
1
625

. . . 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.


But Why?

世界只因有你
世界只因有你

reply all(1)
学习ing

It should be because the execution process of JSON.parse actually undergoes two escapes.

Once is the escape of the string itself:

'{"test": "这是一个对象, 里面有 \"test\" 字段"}'

is converted to

'{"test": "这是一个对象, 里面有 \"test\" 字段"}'

(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

'{"test": "这是一个对象, 里面有 \"test\" 字段"}'

"" 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template