解析json时处理反斜杠 [英] Handling backslash when parsing json
问题描述
以下是我尝试调用JSON.parse的较大JSON字符串的一部分。我得到了臭名昭着的无效字符错误,因为(我相信)反斜杠括号(即路径:\ https://mysite.sharepoint.com/sites/Test \)。
Here is a portion of a larger JSON string that I attempting to call JSON.parse on. I am getting the infamous 'invalid character' error because (I believe) of the backslash parentheses (ie. "path:\"https://mysite.sharepoint.com/sites/Test\").
所有在线解析器我已经尝试了它的工作正常,但在我的javascript代码中JSON.parse方法失败。
All online parsers I have tried it on works fine but in my javascript code the JSON.parse method fails.
我试图像这样和其他方式清理字符串,但我一直在无法解析它。
I have attempted to clean the string like this and other ways but I have been unable to get it to parse.
var cleanData = data.replace(/\\"/, /\\\\/);
下面是部分JSON文件。当我从JSON字符串中删除它时,JSON.parse正常工作,所以我认为我已将此与此隔离。什么类型的通用清洁方法可以解决这个问题? Thansk
below is the partial JSON file. When I remove it from the JSON string the JSON.parse works so I think I have this isolated to just this. What type of general purpose clean method would work to get this thing to parse? 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
}}
如何?
推荐答案
问题是你的反斜杠被作为字符串中的转义字符吞下:
The problem is that your backslash is getting swallowed as an escape character in the string:
'\"' === '"' // true
实际上你需要转义反斜杠,以便JSON解析器看到它们。这是另一个例子:
You actually need to escape the backslashes, so that the JSON parser sees them. Here's another example:
var unencoded = 'string with "quotes"';
'"string with \"quotes\""' === JSON.stringify(unencoded); // false
'"string with \\"quotes\\""' === JSON.stringify(unencoded); // true
但是,应该在哪里进行转义取决于JSON如何可用于JavaScript。如果JSON通过服务器端脚本嵌入到页面中,那么就不需要使用 JSON.parse
,因为有效的JSON是有效的JavaScript:
However, where the escaping should be done depends on how the JSON is being made available to the JavaScript. If the JSON is embedded in the page by a server-side script, then there's no need to use JSON.parse
, as valid JSON is valid JavaScript:
// if JsonData is valid JSON, it's also a valid JavaScript object
var data = <%= JsonData %>;
这篇关于解析json时处理反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!