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

标签 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
    }
  ]
}   

例如,我需要找到一本书,其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?
}

提前致谢。

最佳答案

应该这样做:

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,则必须这样做:

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

关于c++ - jsoncpp。通过匹配值查找数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27902576/

相关文章:

c++ - 获取指针和常规 int 的奇怪值

c++ - 将 (const) char * 转换为 LPCWSTR

c++ - 我想在主程序的函数中使用变量集,但是在声明变量时出错

c++ - 从 JSON 数组获取天气

c++ JsonCpp将带有转义引号的字符串解析为数组

c++ - ‘std::cout << 中 ‘operator<<’ 的模糊重载

c++ - 通过 UV4L 数据通道的 unix 域套接字发送数据

c++ - 如何将 JsonCPP 值作为字符串获取?

c++ - jsoncpp增量写入

c++ - JsonCpp:如何在 Json::Value 中获取空对象?