C++ jsoncpp。通过匹配值查找数组中的对象

C++ jsoncpp。通过匹配值查找数组中的对象,c++,jsoncpp,C++,Jsoncpp,我有一个JSON对象: {"books":[ { "author" : "Petr", "book_name" : "Test1", "pages" : 200, "year" : 2002 }, { "author" : "Petr", "book_name" : "Test2", "pages" : 0, "year" : 0 }, { "aut

我有一个JSON对象:

{"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
    }
  ]
}   
例如,我需要找到一本书,它的
作者
键等于
Petr
。我该怎么做?现在我有一段代码:

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?
}
Json::Value findBook(){
Json::Value root=getRoot();

像这样的事情应该可以:

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
}

您可以将JSON数组作为STL容器进行迭代:

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;
}
std::vector SearchInArray(const-Json::Value&Json,const-std::string&key,const-std::string&Value)
{
断言(json.isArray());
std::矢量结果;
对于(size_t i=0;i!=json.size();i++)
if(json[i][key].asString()==value)
结果:push_back(json[i]);
返回结果;
}
像这样使用它:

std::vector<Json::Value> results = SearchInArray(json["books"], "author", "Petr");
std::vector results=SearchInArray(json[“books”]、“author”、“Petr”);

谢谢。我只是觉得有一些优雅的jsoncpp内置函数可以满足这些需求。@PeterShipilo如果有,我会感到非常惊讶-简单直接的方式对我来说似乎非常优雅和简单。你一直在说“它不起作用”.请养成提出具体问题描述和证据的习惯。“它不起作用”基本上没有用。@LightnessRacesinOrbit嗨。我真的很抱歉。我已经将Barry solution标记为正确的,并且是真的。在我的例子中,问题在于Jetbrains的IDE CLion,它目前仅在EAP版本中可用。IDE在编译项目后启动了旧的应用程序,只是有一些错误。
std::vector<Json::Value> results = SearchInArray(json["books"], "author", "Petr");