user3515814 user3515814 - 1 year ago 231
JSON Question

Reading json files in C++

I'm trying to read in a JSON file. So far I focused on using jsoncpp. However, I'm very new to C++ and the documentation is quite hard to understand for me. Could someone perhaps explain in lay terms what it does?

Say I have an people.json which looks like this:

{Anna : {
"age": 18,
"profession": "student"},
Ben : {
"age" : "nineteen",
"profession": "mechanic"}

What happens when I read this in? Can I create some sort of data structure
which I can index by
as well as
? What would be the data type of
? I thought it would be something similar to a (nested) map, but map values always have to have the same type, don't they?

I have worked with python before and my "goal" (which may be ill-set for C++) is to obtain the equivalent of a nested python dictionary.

Answer Source
  1. Yes you can create a nested data structure people which can be indexed by Anna and Ben. However, you can't index it directly by age and profession (I will get to this part in the code).

  2. The data type of people is of type Json::Value (which is defined in jsoncpp). You are right, it is similar to the nested map, but Value is a data structure which is defined such that multiple types can be stored and accessed. It is similar to a map with a string as the key and Json::Value as the value. It could also be a map between an unsigned int as key and Json::Value as the value (In case of json arrays).

Here's the code:

#include <json/value.h>
#include <fstream>

std::ifstream people_file("people.json", std::ifstream::binary);
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download