Elas Elas - 1 year ago 64
C++ Question

Jsonxx - iterate through Json

I'm using Jsonxx library
I need to iterate through some json values, for example:

"unknowName1" : { "foo" : bar }
"unknowName2" : { "foo" : bar }

It's obvious that I need some sort of iterator, but I can't do it and jsonxx isn't very popular or rich in documentation. Unfortunately I can't use other json library.
I tried this:

Object o;
std::map<std::string, Value*> * jsonMap = o.kv_map;
typedef std::map<std::string, std::map<std::string, std::string>>::iterator it_type;
for (it_type iterator = jsonMap->begin(); iterator != jsonMap->end(); iterator++)
doing stuff here

But jsonxx doesn't provide neither conversion to iterator nor override for "!=" operator.

Answer Source

But jsonxx doesn't provide neither conversion to iterator nor override for "!=" operator.

That's a misconception. There's no need that jsonxx needs to override anything. Their implementation works well just with the standard c++ containers implementations.

As from their (admittedly poorly documented) interface it looks like you need a const_iterator actually

typedef std::map<std::string, std::map<std::string, Value*>>::const_iterator it_type;
                                                                 // ^^^^^^^^

as the kv_map() function returns a const std::map<std::string, Value*>&

Signature as seen in the header:

const std::map<std::string, Value*>& kv_map() const;

also you need to change

std::map<std::string, Value*> * jsonMap = o.kv_map;


const std::map<std::string, Value*>& jsonMap = o.kv_map();
                                // ^                   ^^ it's a function, so call it
                                // | there's no pointer returned but a const reference

to get the syntax right.

Finally the loop should look like this then:

for (it_type iterator = jsonMap.begin(); iterator != jsonMap.end(); ++iterator) {
     // doing stuff here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download