-3

File:

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

how can I read the somestring value by jsoncpp?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Sooran
  • 3
  • 2
  • Basically I want to get the value of key which is "somestring" – Sooran Jun 14 '18 at 01:27
  • 1
    So what problem are you having? Where is your code that tries to do this? – Barmar Jun 14 '18 at 01:29
  • You can use the `getMemberNames()` method to get a vector containing all the property names. `"somestring"` will be the first element of that vector. – Barmar Jun 14 '18 at 01:37

1 Answers1

0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks, it works. And how can I know how many members in my file? Like I want to use a for loop to print all names in my file. – Sooran Jun 14 '18 at 01:52
  • it has a standard iterator, you can loop through all the members. – Barmar Jun 14 '18 at 01:53
  • Similar to looping through a `std::vector` or `std::map` – Barmar Jun 14 '18 at 01:53
  • Can u explain it with some codes? Cuz I just learn a little bit of Jsoncpp, I dont really know how it works. And I haven't learn the vector yet cuz I'm a beginner C++ student. – Sooran Jun 14 '18 at 01:58
  • I've added some simple code, but you'll need to elaborate it to handle your actual object. SO is not a programming school, you need to learn how it works on your own. – Barmar Jun 14 '18 at 02:03