Create a nested json¶
Example on how to create a json object containing more json objects
Will create json:¶
{
"person": {
"name": "Hubert Cumberdale",
"age": 17
},
"vehicles": {
"bicycle": false,
"car": true,
"motorbike": false
}
}
Procedural (C++):¶
// Create empty JsonData of type JSON
Json json = JsonData(JsonBlock());
// Create a JsonBlock to put in 'json'
JsonBlock person;
person.Add("name").SetStringData("Hubert Cumberdale");
person.Add("age").SetIntData(17);
// Create a JsonBlock to put in 'json'
JsonBlock vehicles;
vehicles.Add("bicycle").SetBoolData(false);
vehicles.Add("car").SetBoolData(true);
vehicles.Add("motorbike").SetBoolData(false);
// Now just toss them into 'json'
json.AsJson.Add("person").SetJsonData(person);
json.AsJson.Add("vehicles").SetJsonData(vehicles);
std::cout << json.Render() << std::endl;
Procedural, with shorthands (C++):¶
// Create empty JsonData of type JSON
Json json = JsonBlock();
json.AsJson.ShorthandAdd("person.name").SetStringData("Hubert Cumberdale");
json.AsJson.ShorthandAdd("person.age").SetIntData(17);
json.AsJson.ShorthandAdd("vehicles.bicycle").SetBoolData(false);
json.AsJson.ShorthandAdd("vehicles.car").SetBoolData(true);
json.AsJson.ShorthandAdd("vehicles.motorbike").SetBoolData(false);
std::cout << json.Render() << std::endl;
Add() is ONLY for adding!
Calling Add() with an already existing label/key will result in a JsonLabelAlreadyExistsException.
If you explicitly want to modify an existing value, use Get
("foobar").
SetStringData
("Never gonna up you give");
.
Do note that you can also call Set() which will kind of brute force it. Create the field if it doesn't exist, if it already does, modify it.
Same goes for "Shorthand" functions.
Inline (C++):¶
Json json = JsonData(JsonBlock({
Ele("person", JsonBlock({
Ele("name", "Hubert Cumberdale"),
Ele("age", 17)
})),
Ele("vehicles", JsonBlock({
Ele("bicycle", false),
Ele("car", true),
Ele("motorbike", false)
}))
}));
std::cout << json.Render() << std::endl;