2

I have a JSON string like this:

{"callCommand":{"command":"car","floor":"2","landing":"front"}}

Now, I would like to check if there is a name called command and get the value. Is it possible? My code is as follow, but it doesn't work.

const char json[] = "{\"callCommand\":{\"command\":\"car\",\"floor\":\"2\",\"landing\":\"front\"}}";

rapidjson::Value::ConstMemberIterator itr = d.FindMember("command");

if (itr != d.MemberEnd())
    printf("command = %s\n", d["callCommand"]["command"].GetString());
mtb
  • 1,350
  • 16
  • 32

2 Answers2

3

You are searching for "command" at the top level of the document:

d.FindMember("command");

When you should be searching for it inside "callCommand":

d["callCommand"].FindMember("command");

Also, after you search with FindMember, you should use the iterator instead of searching again using operator[]. Something like:

// assuming that "callCommand" exists
rapidjson::Value& callCommand = d["callCommand"];
rapidjson::Value::ConstMemberIterator itr = callCommand.FindMember("command");

// assuming "command" is a String value
if (itr != callCommand.MemberEnd())
    printf("command = %s\n", itr->value.GetString());
Ian
  • 841
  • 5
  • 10
  • 1
    This solution only work if you know how the json is constructed. FindMember does not work in a recursive way unfortunately – Carlos Vargas Jul 17 '19 at 13:22
-4

You can use rapidjson's HasMember function, as follow:

Document doc;
doc.Parse(json);
doc.HasMember("command");//true or false
mtb
  • 1,350
  • 16
  • 32
gokturk
  • 116
  • 2
  • 13