我已经看到了这个问题的许多不同的答案,并尝试将他们的代码应用到我的项目中,但这些解决方案似乎都不适用于我拥有的数据。
我需要将此输出转换为几个对象:
{“生物”:{“id”:1,“名称”:“R.I.P.”,"sprite_location":null,"health_points":0,“攻击”:0,“防御”:0,"action_points":0,"attack_cost":0}},{“生物”:{“id”:2,“名称”:“R.I.P.”,null“生物”: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,“名称”:“Kappa”,"sprite_location":"http://chunkofwhat.com/games/Parousia/sprites/kappa.gif","health_points":40,“攻击”:6,“防御”:15,"action_points":9,"attack_cost":3}},{“生物”:{“id”:6,“名称”:null,"sprite_location":null,"health_points":null,“攻击”:null,“防御”:null,"action_points":null,“attack_cost”:空}}
当我尝试jQuery.parseJSON()时,它只给了我一堆对象对象,但我不能引用creature1.id等。
再一次,我知道这是一个经常被问到的问题。我真的经历了很多其他的例子,但它们对我来说就是不起作用。
谢谢。
发布于 2012-04-06 20:18:02
每个对象都有一个属性(creature),另一个对象作为它的值。
result_of_parsing_json[1].creature.id发布于 2012-04-06 20:23:27
您的代码似乎完全有效。试试。
var creatures = $.parseJSON(yourJSONString);
alert(creatures[0].creature.name); // alerts "R.I.P"您需要任何具体的澄清吗?
发布于 2012-04-06 20:27:14
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的解析很可能是正确的,但随后出现的逻辑却不正确(完全是猜测)。
https://stackoverflow.com/questions/10043336
复制相似问题