2012-04-06 193 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的解析很可能是正確的,但後來發現的邏輯不是(總猜測)。