Search code examples
c++jsonjsoncpp

How to make jsoncpp throw in this case?


I'm using jsoncpp on ubuntu 14.04. Installed with apt-get libjsoncpp-dev libjsoncpp0. I'm not sure what version of jsoncpp it is.

I had a typo in a key name (in C++) and it was really tricky to track down. Consider this example:

#include <iostream>
#include <jsoncpp/json/json.h>

int main(int argc, char** argv) {
  Json::Reader reader(Json::Features::strictMode());
  Json::Value obj;

  std::string json = "{\"mykey\" : 42}";

  if (!reader.parse(json.c_str(), obj)) {
    std::cout << "JSON parse error" << std::endl;
  }
  const Json::Value& mykey1 = obj["mykey"];
  std::cout << "mykey1:" << mykey1.asInt() << std::endl;

  const Json::Value& mykey2 = obj["mykey_typo"];
  std::cout << "mykey2:" << mykey2.asInt() << std::endl;
  return 0;
}

I'm getting this output:

mykey1:42
mykey2:0

The fact that an access to a non-existent key produces a value of 0 is scary to me. It means if there is a typo the program will just use zero instead of the correct value. I'd rather know there was a typo. Is there a way to make jsoncpp throw or what is the recommended approach here?

I can write a helper that calls isMember and then does the lookup, but was wondering if the library itself has a solution.


Solution

  • It looks like by design the behavior of jsoncpp asInt returns 0 when the value is null. Perhaps do a null check before using the value?

    Take a look at line 721 in the source.