Toby
Toby

Reputation: 3

How to add object member in array?

I have json file like this.

Use nlohmann.

{"Fans": [
        {
            "MemberID": "0",
            "Name": "Fan 0 ABC",
            "Reading": 30
        },
        {
            "MemberID": "1",
            "Name": "Fan 1 ABC",
            "Reading": 40,
            "Unit": "RPM" // add object
        }
]
}

I want find "Fan 1" then add new object.

I can find index of Fans[].

But I don't know how to add object in.

nlohmann::json &tempArray = Resp->res.jsonValue[Fans];
for(auto &x : tempArray.items()) 
{
   auto &Value = x.value();
   auto iter = Value.find("Name");
   if(iter != Value.end())
   {
      std::string str = iter.value();
      if(str.find("Fan 1", 0) != std::string::npos)
      {
           // add object?                                  
      }
   }
}

Upvotes: 0

Views: 2076

Answers (1)

Botje
Botje

Reputation: 30850

I had to restructure your code to produce a MCVE, but you can simply use operator[] to assign new fields to an object:

void modifyJson(json & j) {
    json &tempArray = j["Fans"];
    for(auto &x : tempArray)
    {
        auto iter = x.find("Name");
        if(iter != x.end())
        {
            std::string str = iter.value();
            if(str.find("Fan 1", 0) != std::string::npos)
            {
                x["Unit"] = "RPM";
                return;
            }
        }
    }
}

Upvotes: 1

Related Questions