Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

An overview of the impact of escape characters on JSON.parse in JavaScript


May 08, 2021 JSON


Table of contents


The effect of escape characters on JSON.parse in JavaScript

As explained in the fifth edition of ECMA262, JSON is a built-in object that provides the Stringify and parse methods, which are used to convert js objects into json-compliant strings, and the latter to convert js-compliant strings into js-objects. j son standard reference sl;a href"http://json.org/" rel"external nofollow" target s"_blank" target s"_blank" sgt;json.org sl;/a.gt; (In fact, converting a jason-compliant string into a js object can be used with eval, but eval is relatively poor and has security implications (the code in the jason string is executed), and JSON is only written in this article)

What effect does escape characters have on the JSON.parse method?

Generally speaking, when the parameters of JSON.parse contain transfer characters, there are two escape problems, in fact, the first is the escape of the string itself, the second is the escape of the real js object.

For example:

Example one:

Pass the string ''a':b', 'b': '' to JSON.parse, first the parser extracts the string enclosed in single quotes and thinks that the first ' escapes the second ' 3 ' escapes the first Four, that is, the actual outputable string is.log ."a":"b"," T hen there is an escape when the js object is officially converted, that is, the first escape in the actual output character transition (there are only two at this time). S o .log (JSON.parse ('a':b', 'b': ' The output is Object : "b", b: """"""


Example two:

[javascript]
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 is as follows:

An overview of the impact of escape characters on JSON.parse in JavaScript

According to the escape rule, the actual output of one must have one before this. So if the output on the first line above is written as ''a'::b',""b","

Summary: If you want to appear in the js object, you need to have four in the jason string.

For other special characters:

1. Double quotes ("), if they appear correctly, should be
2. If you think about the correct line-up needs to be in the json string is , in fact, the first pair of the escape, n becomes a normal character, when parsed to the js object n and the previous s (only one) is interpreted as a line-changer. The following two are similar.
3.\r,\\r
4.\t,\\t