Json.Parse逃脱换行符 [英] Json.Parse escape newline characters
问题描述
我在哪里,我试图解析以下使用JSON.parse
'[{姓名JSON字符串页面:鸡蛋,完成:假的,注意事项:注意here\\\
},{名称:糖,完成:假的,注意事项:空}]'
但下面的代码提供误差未捕获的SyntaxError:意外的标记
VAR groceriesJson = JSON.parse(jsonString);
后来我才知道,因为它的 \\\
的JSON字符串。所以,我没有尝试这个解决方案 。但没有运气。还是同样的错误
未捕获的SyntaxError:意外的标记
函数escapeSpecialChars( jsonString){
返回jsonString.replace(/ \\\\
/克,\\\\
)
.replace(/ \\'/克, \\')
.replace(/ \\/克,'\\')
.replace(/ \\&安培/克,\\ \\\&安培;)
.replace(/ \\r /克,\\r)
.replace(/ \\t /克,\ \t)
.replace(/ \\b /克,\\b)
.replace(/ \\f /克,\\ F);
}
VAR groceriesJson = JSON.parse(escapeSpecialChars(jsonString));
任何想法?谢谢
---更新----
我没有创造手动此字符串,我有从C#创建对象JSON字符串C#代码
VAR JSS =新System.Web.Script.Serialization .JavaScriptSerializer();
VAR杂货= jss.Serialize(模型);
然后在JavaScript代码我有
VAR jsonString ='@ Html.Raw(杂货)'
VAR groceriesJson = JSON.parse(escapeSpecialChars(jsonString));
您应该只是逃避 \
在 \\\\
,您的JSON成为:
'[{名:鸡蛋,完成:假的,注意事项:注意here\\\\
},{名称:糖,完成:假的,注意事项:空}]';
如果您不能访问JSON,那么你的功能应该是:
函数escapeSpecialChars(jsonString){
返回jsonString.replace(/ \\\
/克,\\\\
)
.replace(/ \r /克,\\r)
.replace(/ \t /克,\\t)
.replace(/ \f /克,\\f);
}
VAR groceriesJson = JSON.parse(escapeSpecialChars(jsonString));
I have a page where I am trying to parse following json string using JSON.parse
'[{"Name":"Eggs","Complete":false,"Notes":"Notes here\n"},{"Name":"Sugar","Complete":false,"Notes":null}]'
But following code gives error "Uncaught SyntaxError: Unexpected token"
var groceriesJson = JSON.parse(jsonString);
Then I came to know that its because of \n
in json string. So I did try this solution. But no luck. Still same error "Uncaught SyntaxError: Unexpected token"
function escapeSpecialChars(jsonString) {
return jsonString.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
}
var groceriesJson = JSON.parse(escapeSpecialChars(jsonString));
Any ideas? Thanks
---UPDATE----
I am not creating this string manually, I have c# codes that creates json string from c# objects
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var groceries = jss.Serialize(Model);
then in javascript codes I have
var jsonString = '@Html.Raw(groceries)'
var groceriesJson = JSON.parse(escapeSpecialChars(jsonString));
You should just escape the \
as in \\n
, your JSON becoming :
'[{"Name":"Eggs","Complete":false,"Notes":"Notes here\\n"},{"Name":"Sugar","Complete":false,"Notes":null}]';
If you cannot have access to the JSON, then your function should be :
function escapeSpecialChars(jsonString) {
return jsonString.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")
.replace(/\f/g, "\\f");
}
var groceriesJson = JSON.parse(escapeSpecialChars(jsonString));
这篇关于Json.Parse逃脱换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!