json parse error with double quotes

前端 未结 9 1148
悲哀的现实
悲哀的现实 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:34

    If the standard C escapes are added, then JSON.parse will convert sequences like \" into ", \\ into \, \n into a line-feed, etc.

    'foo\\bar\nbaz"' === JSON.parse('"foo\\\\bar\\nbaz\\""')
    

    In our project's case:

    original string ""{\"lat\":28.4594965,\"lng\":77.0266383}""

    After passing to JSON.parse()

    "{"lat":28.4594965,"lng":77.0266383}"
    

    On 2nd pass to JSON.parse()

    {lat: 28.4594965, lng: 77.0266383}
    

    Notice that JSON.parse() removed escaping characters instead of converting string to object.

    After the escaping characters were removed, the string to object conversion worked.

    Here is the demo:

    while (typeof p1 != 'object') {
      p1 = JSON.parse(p1);
      pass++;
      console.log('On pass ', pass, p1);
    }
    

提交回复
热议问题