如何使用 Javascript 解析具有内层的 JSON?
我可以使用 javascript 评估简单的 JSON。
var json = '{"amount":"50","id":"3"}';
var out = eval("{" + json + "}");
现在我将 JPA 与 REST 一起使用,JSON 化的查询结果将包含表名,这使得 JSON 具有内部 JSON,所以简单的 eval 是行不通的。
{"inventory":{"amount":"50","id":"3"}}
我在网上寻找解决方案,但找不到我的案例。
我应该只进行字符串操作并提取 {"amount":"50","id":"3"}
部分吗?
或者还有其他办法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
即使这样也应该有效:
但最好使用 JSON.parse
Even this should work:
But better to use JSON.parse
无论如何,我认为执行简单 eval 的正确方法是将 json 字符串用括号括起来,而不是大括号...
var out = eval("(" + json + ")");
比照。 https://github.com/douglascrockford/JSON-js/blob/master /json.js :
Aniway, I think that the proper way to perform a simple eval is to have the json string surrounded with parenthesis, not curly brackets...
var out = eval("(" + json + ")");
Cf. https://github.com/douglascrockford/JSON-js/blob/master/json.js :
是的,还有另一种(更好的)方法!使用
JSON.parse()
进行解析您的 JSON 并获取您的对象:对于没有本机
JSON
支持的旧版浏览器(例如 IE <8),请包含json2.js
所以上面的方法仍然有效。Yes, there is another (better) way! Use
JSON.parse()
to parse your JSON and get your object out:For older browsers (IE <8 for example) without native
JSON
support, includejson2.js
so this above still works.