If you want to learn how to parse and generate JSON with C++ you have come to the right place.
JsonCpp is a good solid C++ library to work with. The code samples below show that you can easily work with C++ and JSON files. What’s interesting about JSONCPP is that Google uses it in their C++ library for their Data Layer API.
JsonCpp (also known as JSON C++) gives you the ability to open JSON configuration files. This means you can re-use configs and build a faster more performant project out of a frontend web development project. You can use C++ and Node.js and get the best of both worlds through sharing JSON files and JsonCpp!
JsonCpp is great to work with, however the API docs need more of a tutorial. There is a Repl.it instance with code samples that should serve as a better tutorial to help you use the JSON C++ library.
Saving an Object to JSON
Here’s a example of the JSON-specific code to save an object to JSON:
void AddressBook::JsonSave(const char* filename) {
ofstream out(filename, ofstream::out);
Json::Value book_json(Json::objectValue), contacts_json(Json::arrayValue);
for (vector<Contact>::iterator it = contacts_.begin(); it != contacts_.end(); ++it) {
contacts_json.append((*it).ToJson());
}
book_json["contacts"] = contacts_json;
out << book_json;
out.close();
}
Json::Value Contact::ToJson() const {
Json::Value value(Json::objectValue);
value["name"] = name_;
value["phone_number"] = phone_number_;
return value;
}
The above code is also a JSON C++ array example. We are using a vector for a dynamically-sized array, and we are using the JSON C++ arrayValue to extract a list from the JSON.
Loading JSON List/Vector of Objects
Here’s an example of C++ JSON for loading a list/vector of objects from JSON:
void AddressBook::JsonLoad(const char* filename) {
ifstream in(filename);
Json::Value book_json;
in >> book_json;
for (Json::Value::iterator it = book_json["contacts"].begin(); it != book_json["contacts"].end(); ++it) {
AddPerson((*it)["name"].asString(), (*it)["phone_number"].asString());
}
in.close();
}
void AddressBook::AddPerson(string const &name, string const &phone_number) {
Contact contact = Contact();
contact.set_name(name);
contact.set_phone_number(phone_number);
contacts_.push_back(contact);
}
Explanation of Loading JSON C++ Code Example
Okay let’s break down the JSON C++ code above!
First we’re defining a method, JsonLoad, in the AddressBook class. It accepts a filename string argument:
void AddressBook::JsonLoad(const char* filename) {
Then we are creating an input stream using ifstream:
ifstream in(filename);
And we create a variable that will store the parsed JSON value:
Json::Value book_json;
Then all we have to do is pipe the input stream into the JSON value object. The JsonCpp library defines the >> operator and will take care of parsing of the input stream into JSON:
in >> book_json;
Interactive Code Example
Click here to try out and run the code with an interactive example on Repl.it.