Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix an escaped JSON string (JavaScript)

Tags:

A remote server (out of my control) send a JSON string which has all fieldnames and values escaped. For example, when I do JSON.stringify(res), this is the result:

"{\"orderId\":\"123\"}" 

Now when I do alert(res.orderId), it says undefined. I think it's because of the escaped "s. How do I fix this?

like image 858
P.Henderson Avatar asked Sep 08 '14 09:09

P.Henderson


People also ask

How do I remove an escape character from JSON Stringify?

If you simply want to replace the one special character, use: JSON. stringify({ a: 1, b: 2 }, null, '\t');

How do I unescape JSON strings in node JS?

var myJSONString = JSON. stringify(myJSON); var myEscapedJSONString = myJSONString. replace(/\\n/g, "\\n") . replace(/\\'/g, "\\'") .

How do you escape a new line in JSON?

JSON strings do not allow real newlines in its data; it can only have escaped newlines. Snowflake allows escaping the newline character by the use of an additional backslash character.


2 Answers

Assuming that is the actual value shown then consider:

twice_json = '"{\\"orderId\\":\\"123\\"}"'  // (ingore the extra slashes) json = JSON.parse(twice_json)               // => '{"orderId":"123"}' obj = JSON.parse(json)                      // => {orderId: "123"} obj.orderId                                 // => "123" 

Note how applying JSON.stringify to the json value (which is a string, as JSON is text) would result in the twice_json value. Further consider the relation between obj (a JavaScript object) and json (the JSON string).

That is, if the result shown in the post is the output from JSON.stringify(res) then res is already JSON (which is text / a string) and not a JavaScript object - so don't call stringify on an already-JSON value! Rather, use obj = JSON.parse(res); obj.orderId, as per the above demonstrations/transformations.

like image 161
user2864740 Avatar answered Sep 28 '22 10:09

user2864740


the accepted answer not work for me. I use

json = json.replace(/\\/g,""); let arrayObj = JSON.parse(json); 
like image 31
Kenneth Chan Avatar answered Sep 28 '22 11:09

Kenneth Chan