如何修复转义的JSON字符串(JavaScript) [英] How to fix an escaped JSON string (JavaScript)

查看:117
本文介绍了如何修复转义的JSON字符串(JavaScript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

远程服务器(在我的控制之外)发送一个JSON字符串,其中包含所有字段名和值的转义。
例如,当我执行JSON.stringify(res)时,结果如下:

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\"}"

现在当我发出警报时( res.orderId),它表示未定义。我认为这是因为逃脱的's。
如何解决这个问题?

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

推荐答案

假设 显示的实际值然后考虑:

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"

注意如何将JSON.stringify应用于 json 值(这是一个字符串,因为JSON 是文本)会导致 twice_json 值。进一步考虑之间的关系obj (一个 JavaScript对象)和 json (JSON 字符串)。

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).

也就是说,如果帖子中显示的结果是 JSON.stringify(res)的输出 t hen res是已经 JSON( text / a string )而是一个JavaScript对象 - 所以不要在已经上面调用stringify- JSON值!相反,使用 obj = JSON.parse(res); obj.orderId ,按照上面的演示/转换。

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.

这篇关于如何修复转义的JSON字符串(JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆