How to fix JsonCPP error from getMemberNames ()?

The JSON file is as follows:

{
"strings": [
    {
        "key_one": "value_one!"
    },
    {
        "key_two": "value_two!"
    },
    ]
}

A C ++ file is as follows:

Json::Value root;
Json::Reader reader;
bool parsingSuccessful = reader.parse(contents, root);
const Json::Value strings = root["strings"];
std::vector<std::string> list = strings.getMemberNames();

The error caused by "strings.getMemberNames ()":

Assertion failed: (type_ == nullValue || type_ == objectValue), function getMemberNames, file /projects/.../jsoncpp.cpp,

stringsis arrayValue, I confirmed it by receiving it ValueType = 6.

+5
source share
1 answer

As you say, strings are an array, not an object. You need to either: (i) convert your json strings to an object.

{
"strings": {
        "key_one": "value_one!",
        "key_two": "value_two!"
    }
}

In this case, your existing code will be fine. This is what I would do if you have control over the json you are parsing.

or (ii) Iterating over an array of strings - I would only do this if json was specified by some third party. It will look something like this:

std::vector<std::string> all_keys;
for ( int index = 0; index < strings.size(); ++index ) {
    std::vector<std::string> cur_keys = strings[index].getMemberNames();
    all_keys.insert( all_keys.end(), cur_keys.begin(), cur_keys.end() );
}

all_keys - - - .

std::map<std::string,std::string> key_values;
for ( int index = 0; index < strings.size(); ++index ) {
    std::vector<std::string> cur_keys = strings[index].getMemberNames();
    for( int j=0; j<cur_keys.size(); ++j )
      key_values[cur_keys[j]] = ...
}

, , , .

std::vector<std::pair<int,std::string> > all_keys;    std::vector<std::string> all_keys;
for ( int index = 0; index < strings.size(); ++index ) {
    std::vector<std::string> cur_keys = strings[index].getMemberNames();
    for( int j=0; j<cur_keys.size(); ++j )
      all_keys.push_back( std::make_pair(index, cur_keys[j] ) );
}
+5

All Articles