jsoncpp. find object in array by matching value

谁都会走 提交于 2019-12-04 05:05:46

Something like this should do:

std::vector<Json::Value> booksByPeter(const Json::Value& root) {
    std::vector<Json::Value> res;
    for (const Json::Value& book : root["books"])  // iterate over "books"
    {
        if (book["author"].asString() == "Petr")   // if by "Petr"
        {
            res.push_back(book);                   // take a copy
        }
    }
    return res;                                    // and return
}

If not C++11, will instead have to do:

const Json::Value& books = root["books"];
for (Json::ValueConstIterator it = books.begin(); it != books.end(); ++it)
{
    const Json::Value& book = *it;
    // rest as before
}

You can iterate over JSON arrays as STL containers:

std::vector<Json::Value> SearchInArray(const Json::Value &json, const std::string &key, const std::string &value)
{
    assert(json.isArray());
    std::vector<Json::Value> results;
    for (size_t i = 0; i != json.size(); i++)
        if (json[i][key].asString() == value)
            results.push_back(json[i]);
    return results;
}

Use it like this:

std::vector<Json::Value> results = SearchInArray(json["books"], "author", "Petr");
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!