【问题标题】:jsoncpp. find object in array by matching valuejsoncpp。通过匹配值在数组中查找对象
【发布时间】:2015-03-10 06:05:45
【问题描述】:

我有这个 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?
}

提前致谢。

【问题讨论】:

  • 你一直在说“它不起作用”。请养成提供具体问题描述以及证据的习惯。 “不行”基本没用。
  • @LightnessRacesinOrbit 嗨。我真的很抱歉。我已将 Barry 解决方案标记为正确,这是真的。就我而言,问题出在 Jetbrains 的 IDE CLion 上,它目前仅作为 EAP 版本提供。 IDE 有一些错误,在编译项目后它启动了旧应用程序。

标签: c++ jsoncpp


【解决方案1】:

您可以将 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<Json::Value> results = SearchInArray(json["books"], "author", "Petr");

【讨论】:

    【解决方案2】:

    应该这样做:

    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
    }
    

    【讨论】:

    • 谢谢。我只是认为有一些优雅的 jsoncpp 内置函数可以满足这些需求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 2013-09-16
    • 1970-01-01
    • 2019-05-20
    • 2021-07-08
    • 1970-01-01
    • 2021-05-29
    相关资源
    最近更新 更多