How to parse JSON in C++

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.

See Also

How to Read a File in C++

Tue, Oct 4, 2016

Read more →

How to parse JSON in Rust

Fri, Sep 16, 2016

Read more →

How to parse JSON in GO

Sat, Sep 10, 2016

Read more →

How to parse JSON in Elixir

Tue, Sep 6, 2016

Read more →

How to use SQLite in C++

Tue, Jul 9, 2019

Read more →