JSONCPP.通过匹配值查找数组中的对象
jsoncpp. find object in array by matching value
我有这个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
}
您可以将 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");
相关文章:
- 销毁C++中动态分配的内存(数组对象)
- 数组对象的生存期是否在重用其元素存储时结束?
- 为什么顶点数组对象会导致错误?
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- OpenGL 顶点数组对象与 tinyobjloader
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- C++ RapidJson 帮助反序列化数组对象
- ptrdiff_t可以表示指向同一数组对象元素的指针的所有减法吗?
- 检查成员函数是否返回临时对象或数组对象
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 如何使用箭头指针打印出一类数组对象,这些对象中有多个分数
- C++17 std::shared_ptr<> 类数组对象的重载运算符 []
- 添加两个具有运算符重载的数组对象,从而导致分段错误
- opengl:两个不同的矢量可以绑定到同一个顶点数组对象吗
- 使用相同的数据填充数组对象或使用指针
- 方法用于最快的分配,并且不需要将动态大小的数组对象作为局部变量
- 如何将2d数组对象传递给c++中的函数
- ReferenceTable溢出(jni-android),数组对象释放