Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get property name and property value from json-cpp parser?

Tags:

c++

json

jsoncpp

I'm using jsoncpp parser (http://jsoncpp.sourceforge.net) to parse JSON data. So, if we have the following JSON:

{ "name": "Joseph", "age": 20 }

How can I get the property name name and value Joseph, ... after age and 20? OK, we can do universally this:

string e = root.get(propertyName, defaultValue).asString();

But really what we want is something like this:

string e = root.get(name, "Mark").asString();

Now, variable e is Joseph, it works. But I have to take/write "name". I do not want to QUERY (without questioning the function I want to get "name" (name of property) and "Joseph" (value of property)).

After it would be best to store in a field (C/C++ for example):

property[name][0] = "Joseph"
property[age][0] = 20 

How can I do that? Or any other ideas?

like image 915
RePRO Avatar asked Oct 26 '12 00:10

RePRO


1 Answers

You can get all the member names of a Json::Value object using its getMemberNames() function. That returns an object that you can iterate over using .begin() and .end(), like any other standard library container. (In fact, the return type is an alias for std::vector<std::string>.)

After you have the member names, you should be able to iterate through them and use .get(std::string &, const ValueType &) as you already are doing to get the values for each of the object's keys.


Note that JSON objects are inherently unordered, so you can't necessarily rely on that name list having any ordering whatsoever. If you want an ordered object, you should be using JSON arrays, not JSON objects.

like image 84
Platinum Azure Avatar answered Sep 28 '22 05:09

Platinum Azure