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 }, 12 { 13 "name": "C", 14 "inherits": ["A", "B"], 15 "ability": "doTest" 16 } 17 ] 18 }); 19 20 static class EntityMeta { 21 string name; 22 string[] inherits; 23 } 24 25 static class Entity : EntityMeta { 26 string ability; 27 int health = 100; 28 } 29 30 JSONParser[string] states; 31 Entity[string] entities; 32 foreach (index; json.getArray) { 33 34 // Get the metadata and save the state 35 auto state = json.save; 36 auto meta = json.getStruct!EntityMeta; // Efficient and quick way to fetch the two attributes 37 states[meta.name] = state.save; 38 39 // Create the object 40 auto entity = new Entity(); 41 42 // Inherit properties 43 foreach (parent; meta.inherits) { 44 45 // Get the parent 46 auto parentState = states[parent].save; 47 48 // Inherit its values 49 parentState.updateStruct(entity); 50 // Note: We're operating on classes. Use `entity = state.getStruct(entity)` on structs 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.