json parse error with double quotes

前端 未结 9 1174
悲哀的现实
悲哀的现实 2020-12-01 11:38

A double quote even if escaped is throwing parse error.
look at the code below

//parse the json in javascript  
var testJson = \'{\"result\": [\"lunch\",         


        
9条回答
  •  执念已碎
    2020-12-01 12:10

    This problem is caused by the two-folded string escaping mechanism: one comes from JS and one comes from 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.

    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.

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

    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.

    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]);
    

提交回复
热议问题