2

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?

L. F.
  • 19,445
  • 8
  • 48
  • 82
S Andrew
  • 5,592
  • 27
  • 115
  • 237

1 Answers1

1

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)

L. F.
  • 19,445
  • 8
  • 48
  • 82
  • Thanks. What does id means in `for (const auto& [id, time] : times)` – S Andrew Aug 01 '19 at 11:27
  • @SAndrew That's structured binding, a C++17 feature. Since `times` is a map, `id` is bound to the keys in `times` (i.e., `.first` member), and `time` is bound to the corresponding values (i.e., `.second` member). – L. F. Aug 01 '19 at 11:29
  • Got it. Dont know why visual studio says `id` undefined. – S Andrew Aug 01 '19 at 11:32
  • @SAndrew Did you enable C++17? Visual Studio disables C++17 by default AFAIK. – L. F. Aug 01 '19 at 11:32
  • @SAndrew Does [How to enable C++17 compiling in Visual Studio?](https://stackoverflow.com/q/41308933) help? – L. F. Aug 01 '19 at 11:33