Backslash handling when parsing json

Here is a portion of a larger JSON string I'm trying to call JSON.parse. I'm getting the infamous "invalid character" error because (I believe) the backslash brackets (ie Path: \ " https://mysite.sharepoint.com/sites/Test \").

All the online parsers I've tried work fine, but in my javascript code, the JSON.parse method is failing.

I tried to clear the line like this and other ways, but I couldn't parse it.

var cleanData = data.replace(/\\"/, /\\\\/);

      

below is a partial JSON file. When I remove it from the JSON string, JSON.parse works, so I think I have this selection just for this. What type of generic cleanup method should work to get this thing sorted out? Thansk

'{"Properties" : {
    "GenerationId" : 9223372036854776000,
    "indexSystem" : "",
    "ExecutionTimeMs" : 109,
    "QueryModification" : "path:\"https://mysite.sharepoint.com/sites/Test\"  (IsDocument:\"True\" OR contentclass:\"STS_ListItem\") ContentTypeId:0x0120D5200098CBB075E51C8C4398ECCB4B4928912D*",
    "RenderTemplateId" : "~sitecollection/_catalogs/masterpage/Display Templates/Search/Group_Default.js",
    "StartRecord" : 0,
    "piPageImpressionBlockType" : 2
}}

      

as?

+3


source to share


1 answer


The problem is that your backslash is being swallowed as an escape character in the string:

'\"' === '"' // true

      

You really need to avoid backslashes for the JSON parser to see them. Here's another example:



var unencoded = 'string with "quotes"';

'"string with \"quotes\""'   === JSON.stringify(unencoded); // false
'"string with \\"quotes\\""' === JSON.stringify(unencoded); // true

      

However, when the failure should be performed depends on how JSON is made available to JavaScript. If the JSON is embedded in the page server side script, then there is no need to use JSON.parse

as valid JSON is valid JavaScript:

// if JsonData is valid JSON, it also a valid JavaScript object
var data = <%= JsonData %>; 

      

+2


source







All Articles