如何使用 nlohmann C++ 删除嵌套的 json 数据

How to delete nested json data using nlohmann c++

我有以下 json 数据。我在 C++.

中使用 nlohmann json
{
    "CompanyName": "XYZ Tech",
    "Created": "2019-10-16T20:14:29Z",
    "TxnId": "4509237",
    "Tags": [
        {
            "ROIId": "Default",
            "Time": 71,
            "Tracker": "emp10"
        },
        {
            "ROIId": "MC16",
            "Time": 21,
            "TrackerId": "emp10"
        },
        {
            "ROIId": "Default",
            "Time": 11,
            "TrackerId": "emp11"
        },
        {
            "ROIId": "MC18",
            "Time": 10,
            "TrackerId": "emp11"
        }
    ],
    "Type": "TxnData"
}

在上面的 json 数据中,在 Tags 中,我们有 ROIIdDefault 的数据。我想删除它,这样数据就变成了:

{
    "CompanyName": "XYZ Tech",
    "Created": "2019-10-16T20:14:29Z",
    "TxnId": "4509237",
    "Tags": [
        {
            "ROIId": "MC16",
            "Time": 21,
            "TrackerId": "emp10"
        },
        {
            "ROIId": "MC18",
            "Time": 10,
            "TrackerId": "emp11"
        }
    ],
    "Type": "TxnData"
}

我怎样才能在 C++ 中做到这一点。谢谢

我建议遍历 Tags 中存储的 json::array 并保存匹配元素的 Key。这样您以后可以验证删除并安全地删除元素。

请注意,删除与使用 STL 向量擦除完全相同 - 我更喜欢从向量末尾删除,以避免在删除多个元素时更改键。

Here is a quick and dirty demo

代码如下:

#include <iostream>
#include <vector>
#include "json3.6.1.hpp"

unsigned removeDefaultROIID(nlohmann::json& jsonObject, const std::string& value) {
    std::vector<int> toremove;
    //Loop through the `tags` json::array and create a vector of indexes to delete:
    for (auto &it : jsonObject["Tags"].items()) {
    //`.get<std::string>()` is the best way to make sure we are getting the value as std::string
        if (it.value().at("ROIId").get<std::string>() == value) 
            toremove.push_back(stoi(it.key()));
    }
    //sort it before erase - we want to delete first biggest index:
    std::sort(toremove.rbegin(), toremove.rend());
    //delete using `.erase()` method:
    for (int &it : toremove)
        jsonObject["Tags"].erase(jsonObject["Tags"].begin() + it);
    return toremove.size();
}

int main()
{
    //Create the JSON object:
    nlohmann::json jsonObject = R"({"CompanyName":"XYZ Tech","Created":"2019-10-16T20:14:29Z","TxnId":"4509237","Tags":[{"ROIId": "Default","Time": 71,"Tracker": "emp10"},{"ROIId":"MC16","Time": 21,"TrackerId": "emp10"},{"ROIId":"Default","Time":11,"TrackerId":"emp11"},{"ROIId":"MC18","Time": 10,"TrackerId":"emp11"}],"Type":"TxnData"})"_json;

    std::cout << "JSON nested object value conditional erase:" << std::endl;
    std::cout << "JSON object TAGS count - BEFORE deletion:" << jsonObject["Tags"].size() << std::endl;
    //Call the method -> jlson is passed by ref
    unsigned removed = removeDefaultROIID(jsonObject, "Default");

    std::cout << "JSON object TAGS count - AFTER deletion:" << jsonObject["Tags"].size() << std::endl;

    return 0;
}