2012-04-06 21 views
0

Ich habe viele verschiedene Antworten auf diese Frage gesehen und habe versucht, ihren Code auf mein Projekt anzuwenden, aber keine dieser Lösungen scheint für die Daten zu funktionieren, die ich habe.Erstellen eines Objekts aus JSON

Ich brauche diese Ausgabe in mehrere Objekte drehen:

[{ "Kreatur": { "id": 1, "name": "RIP", "sprite_location": null, "health_points": 0 , "Angriff": 0, "Verteidigung": 0, "action_points": 0, "attack_cost": 0}}, {"Kreatur": {"id": 2, "name": "RIP", "sprite_location" : "http://chunkofwhat.com/games/Parousia/sprites/rip.gif", "health_points": 0, "attack": 0, "defense": 0, "action_points": 0, "attack_cost": 0 }}, {"Kreatur": {"id": 3, "Name": "Bull.", "sprite_location": "http://chunkofwhat.com/games/Parousia/sprites/bull.gif", "health_points ": 50," attack ": 8," defense ": 20," action_points ": 9," attack_cost ": 5}}, {" Kreatur ": {" id ": 4," name ":" Swallow. " , "sprite_location": "http://chunkofwhat.com/games/Parousia/sprites/swallow.gif", "health_points": 30, "attack": 12, "defense": 10, "action_points": 13, " attack_cost ": 5 }}, {"Kreatur": {"id": 5, "Name": "Kappa.", "sprite_location": "http://chunkofwhat.com/games/Parousia/sprites/kappa.gif", "health_points ": 40," attack ": 6," defense ": 15," action_points ": 9," attack_cost ": 3}}, {" Kreatur ": {" id ": 6," name ": null," sprite_location ": null," health_points ": null," attack ": null," defense ": null," action_points ": null," attack_cost ": null}}]

Wenn ich versuche, jQuery.parseJSON(), es gibt mir nur eine Reihe von [Objekt Objekt] s, aber ich kann nicht auf Kreatur [1] .id usw.

Ich wieder weiß, dass dies eine häufig gestellte Frage ist. Ich habe wirklich viele andere Beispiele durchgemacht, aber sie haben einfach nicht geklappt.

Vielen Dank.

Antwort

2

Jedes Objekt hat eine Eigenschaft (creature) mit einem anderen Objekt als Wert.

result_of_parsing_json[1].creature.id 
0

Ihr Code scheint einwandfrei zu sein. Versuchen Sie this jsfiddle.

var creatures = $.parseJSON(yourJSONString); 

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

Benötigen Sie spezielle Klarstellungen?

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 
*/ 

Jede Kreatur ist in einem anderen Objekt verschachtelt, und da es eine Reihe von Objekten (die die Kreatur enthält), haben Sie mit einer for Schleife über sie zu durchlaufen, um davon Gebrauch zu machen.

Ihr Parsen des JSON war dann höchstwahrscheinlich korrekt, aber die Logik, die danach kam, war nicht (bei einer Gesamtschätzung).

Verwandte Themen