How to fix JSON escape string (JavaScript)

The remote server (out of my control) sends a JSON string that has all the field names and values. For example, when I do JSON.stringify (res), this is the result:

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

Now when I warn (res.orderId), it says undefined. I think this is because of the flight. How to fix it?

+5
source share
4 answers

Assuming this is the actual value shown, 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 that applying JSON.stringify to a json value (which is a string, since JSON text is text) will result in a twice_json value. Next, consider the relationship between obj (a JavaScript object) and json (a JSON string).

That is, if the result indicated in the message is the output from JSON.stringify(res) , then res is already JSON (which is text / a string), and not a JavaScript object, so do not call stringify for the JSON value already! Rather, use obj = JSON.parse(res); obj.orderId obj = JSON.parse(res); obj.orderId , according to the above demos / conversions.

+12
source

You can use JSON.parse, I really don't know what the API returns for you, so I cannot give you alternatives.

 var res = "{\"orderId\":\"123\"}"; res = JSON.parse(res); alert(res.orderId); 
0
source

This is actually the object on which you are executing JSON.stringufy.

 var jsonString = "{\"orderId\":\"123\"}"; var jsonObject = JSON.parse(jsonString); console.log(jsonObject.orderId); 

Or do you just do it

 var jsonObject = JSON.parse("{\"orderId\":\"123\"}"); console.log(jsonObject.orderId); 
0
source

You really need to strengthen your data, can't use json.orderId? are you saying you are sending json string? you don't need to make lines if your json is already in the line ... If you have a chrome debugger or another browser debugger, you can see the type of your var ...

-1
source

Source: https://habr.com/ru/post/1202061/


All Articles