1

In my application when I enter value as my"name in text field the framework makes a String like (this i can not control):

"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"

Now this String is passed to JSON.parse() method which produces an error because of ambiguous name field as

\"name\":\"my\"name\"

var str = JSON.parse("[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]")

This results in JSON exception

Is there anything I can do with the string:

"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"

To escape double quote character in my " name as my \" name to make it valid for JSON.parse method.

I can not control JSON String, I am just passing name as my"name and framework creates a String which is passed to JSON.parse()

quintin
  • 812
  • 1
  • 10
  • 35
  • Possible duplicate of [JSON.parse string with quotes](http://stackoverflow.com/questions/3066886/json-parse-string-with-quotes) – diziaq Dec 23 '15 at 05:16
  • I am not controlling the JSON string I am just passing the name and framework constructs it for me which I have to manipulate before doing JSON.parse() – quintin Dec 23 '15 at 05:20
  • 2
    Garbage in - garbage out. You or your framework do not know how to escape strings. Show the code - how you "enter value" and pass it to this framework. – Yeldar Kurmangaliyev Dec 23 '15 at 05:20
  • I enter value in a JSP which is read and converted into the JSON string without escaping intelligence framework code is not in my control. So i can only play with the result screen "[{\"id\":\"0\",\"name\":\"\"\",\"colorCode\":\"\",\"version\":\"0\",\"nodeOrder\":\"1\"}]" – quintin Dec 23 '15 at 05:27
  • @rjoshi What will it output if you enter **`my\"name`**, **`my\name`**? – Yeldar Kurmangaliyev Dec 23 '15 at 05:28
  • @Yeldar then it save name as my"name for my\"name and same exception in 2nd case – quintin Dec 23 '15 at 05:31

2 Answers2

0

I went through a series of text replace. You can try this:

var str = "[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]";

JSON.parse(
str.replace(/\\/i,"").
replace(/{"/g,"{'").
replace(/":"/g,"':'").
replace(/","/g,"','").
replace(/"}/g,"'}").
replace(/'/g,"\@@@").
replace(/"/g,"\\\"").
replace(/@@@/g,"\"")
);

It will give back your desired JSON array

Tom Sebastian
  • 3,373
  • 5
  • 29
  • 54
-1
var str = "[{\"id\":\"201500000001002\"}]";
str.replace("\"*","\\\"");
var obj = JSON.parse(str);
arun
  • 107
  • 6
  • `str.replace` won't do anything unless you assign its result back to `str`. Furthermore, this will fail on the OP's example of `\"name\":\"my\"name\"`. –  Dec 23 '15 at 05:28