According to the explanation in the fifth edition of ECMA262, JSON is a built-in object that provides stringify and parse methods. The former is used to convert js objects into strings that conform to json standards, and the latter converts strings that conform to json standards into js objects. . json standard reference json.org . (In fact, you can use eval to convert a string that conforms to the json standard into a js object, but eval has relatively poor performance and has security risks (it will execute the code in the json string). This article only writes JSON)
This article writes about conversion The impact of meaning characters on the JSON.parse method.
Generally speaking, when the parameters of JSON.parse contain transfer characters, you will encounter two escaping problems. In fact, the first time is the escaping of the string itself, and the second time is the actual conversion to Escape of js objects.
An example is as follows:
Example 1: Pass the string '{"a":"b","b":"\\"}' to JSON.parse, first the parser extracts the single quotes When enclosing a string, it is considered that the first one is escaped, the second one is escaped, and the third one is escaped the fourth one. That is to say, the actual output string is {"a":"b","b":"\"} (It can be verified through console.log('{"a":"b","b":"\\"}')), and then there is another escape when it is officially converted into a js object, which is the actual output character. The first one escapes the second one (there are only two at this point). So console.log(JSON.parse('{"a":"b","b":"\\"}') ); the output result is Object {a: "b", b: ""}, also That is to say, the actual displayed data is one (actually one data can be output, indicating that there is another one before this).
Example 2:
var obj = {
a : "b",
b : "\",
c : {
b : "\",
a : {
b : "\"
}
}
};
var json_str = JSON.stringify(obj);
console.log( JSON.stringify(obj) ) ;
console.dir(JSON.parse(json_str));
console.dir(JSON.parse('{"a":"b","b":"\\","c": {"b":"\\","a":{"b":"\\"}}}'));The output result is as shown below
pic
According to the escaping rules, the actual output is There must be one before this one. So the output of the first line above is '{"a":"b","b":"\\","c":{"b":"\\","a":{" b":"\\"}}}', which can be verified by the third output.
To summarize, if you want one to appear in the js object, four need to appear in the json string.
For other special characters
1. Double quotation mark ("), if the double quotation mark appears correctly, it should be \"
2.n, if you think about it, The correct line breaks required in the json string are
, in fact, we first escape the characters in n, and n becomes an ordinary character. When parsed into a js object, n and the previous one (only one left) are interpreted as newlines. The following two are similar to this.
3.r,
4.t,