Search code examples
c++jsonjsoncpp

Reading Json file's root in c++ with jsoncpp


File:

{  
   "somestring":{  
      "a":1,
      "b":7,
      "c":17,
      "d":137,
      "e":"Republic"
   },
}

how can I read the somestring value by jsoncpp?


Solution

  • Use the getMemberNames() method.

    Json::Value root;
    root << jsonString;
    Json::Value::Members propNames = root.getMemberNames();
    std::string firstProp = propNames[0];
    std::cout << firstProp << '\n'; // should print somestring
    

    If you want to see all the properties, you can loop through it using an iterator:

    for (auto it: propNames) {
        cout << "Property: " << *it << " Value: " << root[*it].asString() << "\n";
    }
    

    This simple loop will only work for properties whose values are strings. If you want to handle nested objects, like in your example, you'll need to make it recursive, which I'm leaving as an exercise for the reader.