Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  119] [ 3]  / answers: 1 / hits: 63480  / 10 Years ago, mon, september 8, 2014, 12:00:00

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?


More From » json

 Answers
7

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.


[#69536] Friday, September 5, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
soniap

Total Points: 626
Total Questions: 119
Total Answers: 110

Location: Palestine
Member since Tue, Jul 20, 2021
3 Years ago
soniap questions
Mon, Jun 22, 20, 00:00, 4 Years ago
Fri, May 8, 20, 00:00, 4 Years ago
Fri, Mar 20, 20, 00:00, 4 Years ago
;