S Andrew
S Andrew

Reputation: 7218

How to merge same key json data into one in c++ using nlhoman json

I have below JSON data:

{
    "Created": "2019-08-01T14:36:49Z",
    "Tags": [

        {
            "ObjectId": "1",
            "Time": 6,
            "TrackerId": "W1"

        },

        {
            "ObjectId": "2",
            "Time": 4,
            "TrackerId": "E34"

        },
        {
            "ObjectId": "3",
            "Time": 4,
            "TrackerId": "W1"

        },
        {
            "ObjectId": "4",
            "Time": 8,
            "TrackerId": "E34"
        }
    ],
    "id": 0
}

In the above JSON data, we can see that we have 4 object id's but only 2 tracker id. I need to merge the data which has the same TrackerId and also add their time. So above data will become:

{
    "Created": "2019-08-01T14:36:49Z",
    "Tags": [

        {
            "Time": 10,
            "TrackerId": "W1"

        },

        {
            "Time": 12,
            "TrackerId": "E34"

        }

    ],
    "id": 0
}

I am using Nlohmann JSON library for C++. How can we achieve this?

Upvotes: 2

Views: 1324

Answers (1)

L. F.
L. F.

Reputation: 20579

You can build a map of the trackers and then feed them into the JSON object:

json merge_objects(const json& data)
{
    std::map<std::string, int> times;
    for (const auto& entry : data["Tags"]) {
        times[entry["TrackerId"]] += static_cast<int>(entry["Time"]);
    }

    json result;
    result["Created"] = data["Created"];
    for (const auto& [id, time] : times) {
        json tag;
        tag["Time"] = time;
        tag["TrackerId"] = id;
        result["Tags"].push_back(tag);
    }
    return result;
}

(live demo)

Upvotes: 1

Related Questions