Categories: Portfolio, Software Development

Learning JsonCpp

Learning JsonCpp: a C++ JSON parser tutorial, is a code repo I put together for learning how to parse C++ with JsonCpp.

2017 UPDATE: JsonCpp is a good solid C++ library to work with and I hope the above code sample has given you a nice way to work with C++ and JSON files. What’s interesting about JSONCPP is that even Google uses it in their C++ library for their Data Layer API. Another cool thing about JsonCpp is that it gives you the ability to open JSON configuration files for all those Node.js files, meaning you can re-use configs and build a faster more performant project out of a frontend web development project.

If you aren’t a fan of C++, I’ve also written a Perl6 tutorial on parsing JSON.

Update (29 July 2013): I tagged v1.0.0 of the code on github. It loads and saves a JSON file properly. I ran into a weird issue with iterators but I think that’s my own fault for not completely understanding how to reference/dereference them.

The issue I’m having is that JsonCpp doesn’t seem to be packaged up for distribution on Ubuntu or other distros.

JsonCpp is great to work with, but the API docs need more of a tutorial. I hope that my code in learning-jsoncpp can serve as kind of a tutorial.

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;
}

Here’s an example of 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);
}

You can check out the learning-jsoncpp project with source code on Github to see a fully functioning example of using JSONCPP.