您可以使用可选的reviver 参数来转换它们:
var json = '{"decks": [{"cards":[{"id": 1},{"id": 2},{"id": 3}],"id":3},{"cards":[{"id": 4},{"id": 5},{"id": 6}],"id":4}]}';
function Deck( cards, id ) {
this.cards = cards;
this.id = id;
}
function Card(id) {
this.id = id;
}
var decks = JSON.parse(json, function(key, value ) {
if( key === "decks" ) {
return value.map( function(deck) {
return new Deck( deck.cards, deck.id );
});
}
else if( key === "cards" ) {
return value.map( function( card ) {
return new Card( card.id );
});
}
else {
return value;
}
}).decks;
然后做:
console.log( decks )
给出以下内容: