-
Yes you can create a nested data structure
peoplewhich can be indexed byAnnaandBen. However, you can’t index it directly byageandprofession(I will get to this part in the code). -
The data type of
peopleis of typeJson::Value(which is defined in jsoncpp). You are right, it is similar to the nested map, butValueis a data structure which is defined such that multiple types can be stored and accessed. It is similar to a map with astringas the key andJson::Valueas the value. It could also be a map between anunsigned intas key andJson::Valueas the value (In case of json arrays).
Here’s the code:
//if include <json/value.h> line fails (latest kernels), try also:
// #include <jsoncpp/json/json.h>
#include <json/value.h>
#include <fstream>
std::ifstream people_file("people.json", std::ifstream::binary);
Json::Value people;
people_file >> people;
cout<<people; //This will print the entire json object.
//The following lines will let you access the indexed objects.
cout<<people["Anna"]; //Prints the value for "Anna"
cout<<people["ben"]; //Prints the value for "Ben"
cout<<people["Anna"]["profession"]; //Prints the value corresponding to "profession" in the json for "Anna"
cout<<people["profession"]; //NULL! There is no element with key "profession". Hence a new empty element will be created.
As you can see, you can index the json object only based on the hierarchy of the input data.