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?
If you simply want to replace the one special character, use: JSON. stringify({ a: 1, b: 2 }, null, '\t');
var myJSONString = JSON. stringify(myJSON); var myEscapedJSONString = myJSONString. replace(/\\n/g, "\\n") . replace(/\\'/g, "\\'") .
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.
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.
the accepted answer not work for me. I use
json = json.replace(/\\/g,""); let arrayObj = JSON.parse(json);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With