2012-04-06 174 views
0

我已经看到了很多不同的问题答案,并试图将他们的代码应用到我的项目中,但这些解决方案似乎都不适用于我拥有的数据。从JSON创建对象

我需要把这个输出成几个对象:

[{ “生物”:{ “ID”:1, “名”: “RIP”, “sprite_location”:空, “health_points”:0 , “攻击”:0, “防守”:0, “action_points”:0, “attack_cost”:0}},{ “生物”:{ “ID”:2, “名”: “RIP”, “sprite_location” : “http://chunkofwhat.com/games/Parousia/sprites/rip.gif”, “health_points”:0, “攻击”:0, “防守”:0, “action_points”:0, “attack_cost”:0 }},{ “生物”:{ “ID”:3 “名称为”: “公牛”, “sprite_location”: “http://chunkofwhat.com/games/Parousia/sprites/bull.gif”,“health_points “:50,” 攻击 “:8,” 防守 “:20,” action_points “:9”,attack_cost “:5}},{” 生物 “:{” ID “:4”,名称 “:”。燕子” “sprite_location”: “http://chunkofwhat.com/games/Parousia/sprites/swallow.gif”, “health_points”:30, “攻击”:12, “防守”:10, “action_points”:13” attack_cost“:5 }},{ “生物”:{ “ID”:5 “名称为”: “卡帕”, “sprite_location”: “http://chunkofwhat.com/games/Parousia/sprites/kappa.gif”,“health_points “40,” 攻击 “:6,” 防守 “:15,” action_points “:9,” attack_cost “:3}},{” 生物 “:{” ID “:6,” 名 “:空,” sprite_location “:null,”health_points“:null,”attack“:null,”defense“:null,”action_points“:null,”attack_cost“:null}}]

当我尝试jQuery.parseJSON只是给了我一堆[object Object],但我不能参考生物[1] .id等。

同样,我知道这是一个经常被问到的问题。我真的已经经历了许多其他的例子,但他们只是没有为我工作。

谢谢。

回答

2

每个对象都有一个属性(creature)与另一个对象,因为它的值。

result_of_parsing_json[1].creature.id 
0

您的代码似乎完全有效。尝试this jsfiddle

var creatures = $.parseJSON(yourJSONString); 

alert(creatures[0].creature.name);​ // alerts "R.I.P" 

您是否需要任何具体的说明?

0
var creatures = JSON.parse('big_json_string'); 

for (var i = 0; i < creatures.length; i++) { 
    var creature = creatures[i].creature; // this is how your object is formatted 

    console.log(creature.name); 
} 

/* 
R.I.P. 
R.I.P. 
Bull. 
Swallow. 
Kappa. 
null 
*/ 

每个生物嵌套在另一个对象中,并且因为它是对象的数组(包含生物),你必须遍历其与for循环,以利用它。

然后,您对JSON的解析很可能是正确的,但后来发现的逻辑不是(总猜测)。