简体   繁体   English

如何将字符串化对象中的双引号转义以将其解析为有效的 JSON?

[英]How to escape double quotes in stringified object to PARSE IT into valid JSON?

I have a list in C#.我在 C# 中有一个列表。 In my page, I give this list with : '@Html.Raw(Json.Encode(Model.MyList))';在我的页面中,我给出了这个列表:'@Html.Raw(Json.Encode(Model.MyList))';

I stringify this object, the obj is good.我把这个对象串起来,obj很好。

But when I try to parse it to an object JSON with 'JSON.parse', I have this exception 'Unexpected token , in JSON at position 26 SyntaxError: Unexpected token , in JSON at position 26 at JSON.parse ()'.但是,当我尝试使用“JSON.parse”将其解析为对象 JSON 时,我有此异常“意外的令牌,在 JSON 中的位置 26 SyntaxError: Unexpected token,在 JSON 中的位置 26 处的 JSON.parse()”。

This is because of the double quotes in some keys of this object, like "Example4".这是因为该对象的某些键中的双引号,例如“Example4”。

      "Example2":"C01150",
      "Example3":"C01150",
      "Example4":"vase pompe de flèche ATC T 16"","
      "Example5":false," 
     },

I have tried this solution : https://salesforce.stackexchange.com/questions/233068/replace-double-quotes-with-single-quote-in-a-json-string我试过这个解决方案: https ://salesforce.stackexchange.com/questions/233068/replace-double-quotes-with-single-quote-in-a-json-string

And this one : How to escape double quotes in JSON还有这个: 如何在 JSON 中转义双引号

So, I do this : function jsonEscape(str) { return str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g,"\\\\t").replace(/\\"/, '\\"');}所以,我这样做: function jsonEscape(str) { return str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g,"\\\\t").replace(/\\"/, '\\"');}

But the double quotes don't move...但是双引号不动...

JSON.parse result : JSON.parse 结果:

"Example4":"vase pompe de flèche ATC T 16"","

I am trying to get this code :我正在尝试获取此代码:

"Example4": "vase pompe de flèche ATC T 16\"",

I want a valid JSON object.我想要一个有效的 JSON 对象。

Can someone help me ?有人能帮我吗 ?

The last bit of regex,正则表达式的最后一点,

replace(/\\"/, '\\"')

is looking for the sequence \" not "正在寻找序列\" not "

If it read,如果读了,

replace(/"/g, '\"')

then it would look for every instance ( g lobally) of " and replace it with an escaped version \" safe for the parser.然后它将查找 " 的每个实例(全局g "并将其替换为对解析器安全的转义版本\"

try this尝试这个

var str = `{
      "Example2":"C01150",
      "Example3":"C01150",
      "Example4":"vase pompe de flèche ATC T 16"","
      "Example5":false
     }`;
var arr = [];
var arrStr = str.replace("{", "").replace("}", "").split("\n");
arrStr.forEach((item) => {
  arr.push(item.trim().split(":"));
});
str = "";
for (let index = 0; index < arr.length; index++) {
  if (arr[index][1] == undefined) continue;
  arr[index][1] = arr[index][1].replace('"",', "").replace(",", "");
  console.log(arr[index][1]);
  str = str + arr[index][0] + ":" + arr[index][1] + ",";
}

str = "{" + str.substring(0, str.length - 1) + "}";
console.log(JSON.parse(str));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM