Amir-Mousavi
Amir-Mousavi

Reputation: 4563

c++, JSON, get object members in an array

I am using nlohmann::json for parsing json in the program.

given a json there is an array with several objects, according to one of the object members I want to get other members of the same object.

like in the json below

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

for instance if the value of a is 2, I want to get the values of b,c,... of the same index/object.

currently I am using a for loop and at the index that j["arr"][i]["a"].get<int> == 2 going for the rest of members. As the array might have hundreds of members it is nonsense.

what is the best approach in this case?

Upvotes: 1

Views: 3749

Answers (2)

Caleth
Caleth

Reputation: 63152

Let's call the C++ type of the elements of arr Thing, you can convert arr to a std::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

Upvotes: 1

rioki
rioki

Reputation: 6118

It's a JSON array, you need to iterate over it. So your approach is the simple and direct one.

Upvotes: 1

Related Questions