如何使用Javascript解析具有内层的JSON?

时间:2010-12-16 10:04:29

标签: javascript json parsing

我可以用javascript评估简单的JSON。

var json = '{"amount":"50","id":"3"}';
var out = eval("{" + json + "}");

现在我正在使用带有REST的JPA,而JSON-nized查询结果将包含表名 具有内部JSON的JSON如此简单的eval将无法工作。

{"inventory":{"amount":"50","id":"3"}}

我环顾网络寻求解决方案,但无法找到我的案例。 我应该只进行字符串操作并提取{"amount":"50","id":"3"}部分吗? 或者还有其他方式吗?

3 个答案:

答案 0 :(得分:3)

是的,还有另一种(更好的)方式!使用JSON.parse()解析您的JSON并获取您的对象:

var obj = JSON.parse(jsonString);
//then, for example...
var amount = obj.inventory.amount;

对于没有原生JSON支持的旧版浏览器(例如IE< 8),请添加json2.js,因此上述内容仍可正常使用。

答案 1 :(得分:1)

即使这应该有效:

var json = '{"inventory":{"amount":"50","id":"3"}}';
var out = eval("{" + json + "}");

alert(out.inventory.amount);

但最好使用JSON.parse

答案 2 :(得分:0)

Aniway,我认为执行简单eval的正确方法是让json字符串用括号括起来,而不是大括号......

var out = eval(“(”+ json +“)”);

比照。 https://github.com/douglascrockford/JSON-js/blob/master/json.js

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');