Saving parser state
1 auto json = JSONParser(q{ 2 [ 3 { 4 "name": "A", 5 "ability": "doFoo", 6 "health": 30 7 }, 8 { 9 "name": "B", 10 "ability": "doBar", 11 "health": null 12 }, 13 { 14 "name": "C", 15 "inherits": ["A", "B"], 16 "ability": "doTest" 17 } 18 ] 19 }); 20 21 static class EntityMeta { 22 string name; 23 string[] inherits; 24 } 25 26 static class Entity : EntityMeta { 27 string ability; 28 int health = 100; 29 } 30 31 JSONParser[string] states; 32 Entity[string] entities; 33 foreach (index; json.getArray) { 34 35 // Get the metadata and save the state 36 auto state = json.save; 37 auto meta = json.getStruct!EntityMeta; // Efficient and quick way to fetch the two attributes 38 states[meta.name] = state.save; 39 40 // Create the object 41 auto entity = new Entity(); 42 43 // Inherit properties 44 foreach (parent; meta.inherits) { 45 46 // Get the parent 47 auto parentState = states[parent].save; 48 49 // Inherit its values 50 parentState.updateStruct(entity); 51 52 } 53 54 // Now, add local data 55 state.updateStruct(entity); 56 57 entities[entity.name] = entity; 58 59 } 60 61 const a = entities["A"]; 62 assert(a.name == "A"); 63 assert(a.ability == "doFoo"); 64 assert(a.health == 30); 65 66 const b = entities["B"]; 67 assert(b.name == "B"); 68 assert(b.ability == "doBar"); 69 assert(b.health == 100); 70 71 const c = entities["C"]; 72 assert(c.name == "C"); 73 assert(c.ability == "doTest"); 74 assert(c.health == 30); // A had explicitly stated health, B did not — inherited from A. 75 // Otherwise impossible without saving states. 76
Copy the parser. Useful to keep document data for later.