Home > Software design >  How to escape double quotes in stringified object to PARSE IT into valid JSON?
How to escape double quotes in stringified object to PARSE IT into valid JSON?

Time:07-12

I have a list in C#. In my page, I give this list with : '@Html.Raw(Json.Encode(Model.MyList))';

I stringify this object, the obj is good.

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 ()'.

This is because of the double quotes in some keys of this object, like "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

And this one : How to escape double quotes in JSON

So, I do this : 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 :

"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.

Can someone help me ?

CodePudding user response:

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

CodePudding user response:

The last bit of regex,

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

is looking for the sequence \" not "

If it read,

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

then it would look for every instance (globally) of " and replace it with an escaped version \" safe for the parser.

  • Related