javascript Json.Parse 转义换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26420926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:57:10  来源:igfitidea点击:

Json.Parse escape newline characters

javascriptc#regexjsonescaping

提问by sanjeev

I have a page where I am trying to parse following json string using JSON.parse

我有一个页面,我正在尝试使用 JSON.parse 解析以下 json 字符串

'[{"Name":"Eggs","Complete":false,"Notes":"Notes here\n"},{"Name":"Sugar","Complete":false,"Notes":null}]'

But following code gives error "Uncaught SyntaxError: Unexpected token"

但是下面的代码给出了错误 "Uncaught SyntaxError: Unexpected token"

var groceriesJson = JSON.parse(jsonString);

Then I came to know that its because of \nin json string. So I did try this solution. But no luck. Still same error "Uncaught SyntaxError: Unexpected token"

然后我才知道这是因为\n在 json 字符串中。所以我确实尝试了这个解决方案。但没有运气。还是一样的错误"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

我不是手动创建这个字符串,我有从 c# 对象创建 json 字符串的 c# 代码

 var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
 var groceries = jss.Serialize(Model);

then in javascript codes I have

然后在javascript代码中我有

var jsonString = '@Html.Raw(groceries)'
 var groceriesJson = JSON.parse(escapeSpecialChars(jsonString));

回答by laruiss

You should just escape the \as in \\n, your JSON becoming :

您应该将\as in转义\\n,您的 JSON 变为:

'[{"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 :

如果您无法访问 JSON,那么您的函数应该是:

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

回答by Reinaldo

As @Quentin suggests you can skip storing the value inside the literal and simply do something like this:

正如@Quentin 建议的那样,您可以跳过将值存储在文字中,只需执行以下操作:

var jsonObject = @Html.Raw(groceries);