开发者

How to parse JSON that has inner layers using Javascript?

开发者 https://www.devze.com 2023-01-30 16:52 出处:网络
I can eval simple JSON with javascript. var json = \'{\"amount\":\"50\",\"id\":\"3\"}\'; var out = eval(\"{\" + json + \"}\");

I can eval simple JSON with javascript.

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

Now I am using JPA with REST and JSON-nized query result would include table name which makes JSON having inner JSON so simple eval wouldn't work.

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

I've looked around the web for solution but can't find my 开发者_高级运维case. Should I just do string manipulation and extract {"amount":"50","id":"3"} part? Or is there other way?


Yes, there is another (better) way! Use JSON.parse() to parse your JSON and get your object out:

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

For older browsers (IE <8 for example) without native JSON support, include json2.js so this above still works.


Even this should work:

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

alert(out.inventory.amount);

But better to use JSON.parse


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 :

// 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 + ')');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号