PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 25, 2022

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

 July 25, 2022     c#, javascript, json     No comments   

Issue

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 ?


Solution

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


Answered By - Serge
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing