jsoncpp。通过匹配值在数组中查找对象 [英] jsoncpp. find object in array by matching value

查看:1578
本文介绍了jsoncpp。通过匹配值在数组中查找对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个JSON对象:

I have this JSON object:

{"books":[
    {
      "author" : "Petr",
      "book_name" : "Test1",
      "pages" : 200,
      "year" : 2002
    },
    {
      "author" : "Petr",
      "book_name" : "Test2",
      "pages" : 0,
      "year" : 0
    },
    {
      "author" : "STO",
      "book_name" : "Rocks",
      "pages" : 100,
      "year" : 2002
    }
  ]
}   

例如,我需要找一本书) author 键等于 Petr 。我如何做到这一点?现在我有这段代码:

For example, I need to find a book(s) which author key is equal to Petr. How can I do this? Right now I have this piece of code:

Json::Value findBook(){
    Json::Value root = getRoot();

    cout<<root["books"].toStyledString()<<endl; //Prints JSON array of books mentioned above

    string searchKey;
    cout<<"Enter search key: ";
    cin>>searchKey;

    string searchValue;
    cout<<"Enter search value: ";
    cin>>searchValue;

    Json::Value foundBooks = root["books"]???; // How can I get here a list of books where searchKey is equal to searchValue?
}

提前感谢。

推荐答案

这样的操作应该是:

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
}

如果不是C ++ 11, :

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
}

这篇关于jsoncpp。通过匹配值在数组中查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆