Reputation: 159
From a Json string (or file), I want to collect key/value pairs without knowing the keys in advance. Let's say I have this Json:
{ "a":"1","b":"2","c":"3" }
I'd like to collect all key strings "a" , "b" , "c" , "d" and their respective values. BTW: I use rapidjson integration in Cocos2dX 3.3. Any idea?
What I'm on now is to use :
rapidjson::Document JSON;
//..... collecting the JSON .... then
for (rapidjson::Value::MemberIterator M=JSON.MemberonBegin(); M!=JSON.MemberonEnd(); M++)
{
//..... I have access to M->name and M->value here
//..... but I don't know how to convert them to std::string or const char*
}
But I'm stuck with that.
Upvotes: 2
Views: 5440
Reputation: 159
I've just figured out that rapidjson::Value::MemberIterator has functions in it. So here is an example to enumerate key/pairs from a Json document. This example only log root keys. You will need extra work to retrieve sub-keys
const char *jsonbuf = "{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"}";
rapidjson::Document JSON;
rapidjson::Value::MemberIterator M;
const char *key,*value;
JSON.Parse<0>(jsonbuf);
if (JSON.HasParseError())
{
CCLOG("Json has errors!!!");
return;
}
for (M=JSON.MemberonBegin(); M!=JSON.MemberonEnd(); M++)
{
key = M->name.GetString();
value = M->value.GetString();
if (key!=NULL && value!=NULL)
{
CCLOG("%s = %s", key,value);
}
}
Upvotes: 5