Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json Cpp isMember() Returns True always

Tags:

c++

json

For example in a simple json

{
    "A" :
    {
       "B" :
       {
         --something--
       }
    }
}

First Case:

json::Value root;
const Json::Value x = root["A"]["B"];
if (root.isMember("A")) --- always returns TRUE..

Second Case:

Json::Value root;
If (root.isMember("A"))  ---- works fine
const Json::Value x = root["A"]["B"]; 

Any idea what's wrong with First Case? even if I get x before isMember() call.

like image 619
Abhishek Chandel Avatar asked Jan 25 '14 05:01

Abhishek Chandel


Video Answer


1 Answers

Take a look at documentation.

Value &     operator[] (const char *key)
    Access an object value by name, create a null member if it does not exist. 
const Value &   operator[] (const char *key) const
    Access an object value by name, returns null if there is no member with that name. 
Value &     operator[] (const std::string &key)
    Access an object value by name, create a null member if it does not exist. 
const Value &   operator[] (const std::string &key) const
    Access an object value by name, returns null if there is no member with that name. 

Basically, you are creating the member "A" on root["A"] call. To avoid this always check isMember before actually accessing the member (or call it only on const object and do a null check instead - I'd preffer the former).

like image 200
Mateusz Kubuszok Avatar answered Oct 22 '22 21:10

Mateusz Kubuszok