使用nlohmann json

时间:2019-07-09 03:33:35

标签: c++ json nlohmann-json

我正在使用nlohmann json创建并保存一些json值。但是当我查看文件时,我在json之间得到了null值。下面是它的外观:

{
    "Created": "2019-07-03T13:54:32Z",
    "DataId": "BHI-201-U8",
    "Data": [
        {
            "Name": "Andrew",
            "Attended": "Yes"
        },
        {
            "Name": "John",
            "Attended": "Yes"
        },
        null,    <-- unexpected null
        {
            "Name": "Ronny",
            "Attended": "No"
        },
        null,    <-- unexpected null
        null,    <-- unexpected null
        {
            "Name": "Mathew",
            "Attended": "Yes"
        }
    ],
    "Type": "Person"

}

如您在上面的json数据中看到的,我得到了一些意外的null。以下是我的保存方式:

#include "nlohmann/json.hpp"

using nlohmann::json;

int main()
{
    json outJson;

    //some code

    string outFile = "output.json";

    for (const auto &data : trackedData->Detections()) 
    {
        //some code

        outJson["Data"][data.id]["Name"] = data.name;
        outJson["Data"][data.id]["Attended"] = data.status;

    }

    outJson["Created"] = created;
    outJson["DataId"] = "BHI-201-U8";
    outJson["Type"] = "Person";

    std::ofstream output_file(outFile);
    output_file << outJson.dump(4 , ' ', false);

    output_file.close();

}

如何从代码中删除这些多余的null

1 个答案:

答案 0 :(得分:1)

trackedData->Detections()返回对象或结构的列表,其中一些为空值,因此json中为空。在将数据条目添加到json之前,尝试进行null检查。

for (const auto &data : trackedData->Detections()) 
{
    //some code
    if (data != NULL)
    {
        outJson["Data"][data.id]["Name"] = data.name;
        outJson["Data"][data.id]["Attended"] = data.status;
    }

}