-1

I am using nlohmann json to create ans save some json values. But when I look at the file, I get null values in between the json. Below is how it looks like:

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

}

As you can see in the above json data, I am getting some unexpected null. Below is how I am saving it:

#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();

}

How can I remove these extra null from the code.

S Andrew
  • 5,592
  • 27
  • 115
  • 237

1 Answers1

1

trackedData->Detections() returns a list of objects or structures and some of them are null-valued, hence nulls in the json. Try to do null-checking before adding data entry into json.

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;
    }

}
Shamrai Aleksander
  • 13,096
  • 3
  • 24
  • 31
mangusta
  • 3,470
  • 5
  • 24
  • 47