如何使用nlhoman json在C ++中将相同的关键json数据合并为一个

时间:2019-08-01 10:04:54

标签: c++ json nlohmann-json

我有以下JSON数据:

{
    "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
}

在上面的JSON数据中,我们可以看到我们有4个对象ID,但只有2个跟踪器ID。我需要合并具有相同TrackerId的数据,并添加它们的时间。因此,以上数据将变为:

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

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

        },

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

        }

    ],
    "id": 0
}

我正在将Nlohmann JSON library用于C ++。我们如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

您可以构建跟踪器的地图,然后将其输入JSON对象:

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