如何修复转义的 JSON 字符串 (JavaScript)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25721164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fix an escaped JSON string (JavaScript)
提问by P.Henderson
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:
远程服务器(不受我控制)发送一个 JSON 字符串,其中所有字段名和值都已转义。例如,当我执行 JSON.stringify(res) 时,结果如下:
"{\"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?
现在,当我执行 alert(res.orderId) 时,它显示未定义。我认为这是因为转义的“s。我该如何解决这个问题?
回答by user2864740
Assuming that isthe 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 jsonvalue (which is a string, as JSON is text) would result in the twice_jsonvalue. Further consider the relation between obj(a JavaScript object) and json(the JSON string).
请注意如何将 JSON.stringify 应用于json值(这是一个string,因为 JSON是 text)将导致该twice_json值。进一步考虑obj(JavaScript 对象)和json(JSON字符串)之间的关系。
That is, if the result shown in the post is the output from JSON.stringify(res)then res is alreadyJSON (which is text / a string) and nota 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.stringify(res)那么 res已经是JSON(即text / a string)而不是JavaScript 对象 - 所以不要对已经是 JSON 的值调用 stringify!相反,obj = JSON.parse(res); obj.orderId根据上述演示/转换使用 。
回答by sadrzadehsina
It's actually an object that you execute JSON.stringufy on it.
它实际上是一个您在其上执行 JSON.stringufy 的对象。
var jsonString = "{\"orderId\":\"123\"}";
var jsonObject = JSON.parse(jsonString);
console.log(jsonObject.orderId);
Or you do simple than that
或者你做的比那简单
var jsonObject = JSON.parse("{\"orderId\":\"123\"}");
console.log(jsonObject.orderId);
回答by Iman Mohamadi
You can use JSON.parse, I don't really know what that API returns for you so I can't give you alternatives.
您可以使用 JSON.parse,我真的不知道该 API 为您返回什么,因此我无法为您提供替代方案。
var res = "{\"orderId\":\"123\"}";
res = JSON.parse(res);
alert(res.orderId);
回答by cyril
Do you really need to stringify your data can not juste use json.orderId ? you say send you a json string ? you have not to do stringify if your json is already in string.... if you have chrome debugger or another browser debugger you can see the type of your var...
你真的需要字符串化你的数据不能使用 json.orderId 吗?你说给你发送一个json字符串?如果您的 json 已经在字符串中,您不必进行字符串化...如果您有 chrome 调试器或其他浏览器调试器,您可以看到您的 var 的类型...

