1

nlohmann::json用于在程序中解析 json。

给定一个json,有一个包含多个对象的数组,根据我想要获取同一对象的其他成员的对象成员之一。

就像在下面的 json

{
 "arr":[
    {"a":1, "b":11, "c":111, ...},
    {"a":2, "b":22, "c":222, ...},
    {"a":3, "b":33, "c":333, ...},
    ...
   ]
}

例如,如果值为ais 2,我想获取同一索引/对象的 b,c,... 的值。

目前我正在使用一个 for 循环,并在索引处j["arr"][i]["a"].get<int> == 2为其他成员使用。由于数组可能有数百个成员,这是无稽之谈。

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

4

2 回答 2

1

让我们调用 的元素的 C++ 类型arr Thing,您可以转换arrstd::vector<Thing>.

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
于 2018-11-19T10:16:31.240 回答
1

这是一个 JSON 数组,您需要对其进行迭代。所以你的方法是简单直接的。

于 2018-11-19T09:35:54.337 回答