jsoncpp.通过匹配值在数组中查找对象

Pet*_*ila 7 c++ jsoncpp

我有这个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
    }
  ]
}   
Run Code Online (Sandbox Code Playgroud)

例如,我需要找一本author键等于的书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?
}
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Bar*_*rry 8

这样的事情应该做:

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
}
Run Code Online (Sandbox Code Playgroud)

如果不是C++ 11,则必须这样做:

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

  • @PeterShipilo如果有的话,我会非常惊讶 - 只是这样做,直截了当的方式对我来说似乎很优雅和简单. (2认同)