Fri, Sep 16, 2016
Read in 1 minutes
In C++ there are no built-in ways to handle json. However there are many open source libraries to help you.
One of the more popular ones is JsonCpp - and it is relatively easy to use.
Include jsoncpp.cpp in your build, and include json.h where you want to handle json.
std::ifstream json_file("person.json", std::ifstream::binary); Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse( json_file, root, false ); std::string = root["name"].asString(); int age = root["age"].asInt();
First we [open the file]() - and then define a variable to hold the root value of the parsed json.
Next we setup the reader, and parse the file. The resulting Json::Value is quite nice. You can get sub keys by the operator method (like the example above) and call asInt, asFloat, asBool and asString on the result. Or you can iterate over it, if it is an array.