Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;,JSON,获取数组中的对象成员_C++_Json_Nlohmann Json - Fatal编程技术网

C++ c++;,JSON,获取数组中的对象成员

C++ c++;,JSON,获取数组中的对象成员,c++,json,nlohmann-json,C++,Json,Nlohmann Json,我使用nlohmann::json在程序中解析json 给定一个json,有一个包含多个对象的数组,根据其中一个对象成员,我希望获得同一对象的其他成员 就像下面的json一样 { "arr":[ {"a":1, "b":11, "c":111, ...}, {"a":2, "b":22, "c":222, ...}, {"a":3, "b":33, "c":333, ...}, ... ] } 例如,如果a的值是2,我想得到b,c,。。。相同索引/对象的

我使用
nlohmann::json
在程序中解析json

给定一个json,有一个包含多个对象的数组,根据其中一个对象成员,我希望获得同一对象的其他成员

就像下面的json一样

{
 "arr":[
    {"a":1, "b":11, "c":111, ...},
    {"a":2, "b":22, "c":222, ...},
    {"a":3, "b":33, "c":333, ...},
    ...
   ]
}
例如,如果
a
的值是
2
,我想得到b,c,。。。相同索引/对象的

目前我正在使用一个for循环,索引为
j[“arr”][I][“a”].get==2
用于其他成员。由于数组可能有数百个成员,这是胡说八道


在这种情况下,最好的方法是什么?

这是一个JSON数组,您需要对它进行迭代。因此,您的方法是简单直接的。< / P > < P>将C++的类型称为“代码> ARR < /COD> <代码> Test< /COD>,可以将<代码> ARR < /C> >转换为<代码> STD::vector < /C> > /<
void to_json(nlohmann::json&j,const Thing&t){
j=nlohmann::json{{“a”,t.a},{“b”,t.b},{“c”,t.c};//类似地,其他成员。。。
}
void from_json(const nlohmann::json&j,Thing&t){
j、 在(“a”)。到达(t.a);
j、 在(“b”)。到达(t.b);
j、 at(“c”)。get_to(t.c);//类似地,其他成员。。。
}
std::vector things=j[“arr”];
auto it=std::find_if(things.begin()、things.end()、[](const Thing&t){return t.a==2;});
//使用它->b等
void to_json(nlohmann::json & j, const Thing & t) {
    j = nlohmann::json{{"a", t.a}, {"b", t.b}, {"c", t.c}}; // similarly other members ...
}

void from_json(const nlohmann::json & j, Thing & t) {
    j.at("a").get_to(t.a);
    j.at("b").get_to(t.b);
    j.at("c").get_to(t.c); // similarly other members ...
}

std::vector<Thing> things = j["arr"];
auto it = std::find_if(things.begin(), things.end(), [](const Thing & t){ return t.a ==2; });
// use it->b etc