使用Nlohmann JSON将JSON数据保存在文件中时获取空值

Getting null values while saving json data in file using nlohmann json

本文关键字:JSON 获取 文件 空值 保存 Nlohmann 数据 使用 存在      更新时间:2023-10-16

我正在使用nlohmann json创建ANS保存一些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数据中看到,我会得到一些意外的空。以下是我保存的方式:

#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

trackedData->Detections()返回对象或结构的列表,其中一些是无效的,因此在JSON中nulls。在将数据输入添加到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;
    }
}