使用Nlohmann JSON将JSON数据保存在文件中时获取空值
Getting null values while saving json data in file using nlohmann json
我正在使用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;
}
}
相关文章:
- 如何在 nlohmann 的 json 库中获取数组长度?
- UE4 C++ 我无法将 JSON 嵌套值获取到 TArray
- 获取嵌套的 JSON 数组和矩阵C++
- Rapidjson 遍历并获取复杂 JSON 对象成员的值
- C++ nlohmann JSON 获取数组名称
- 如何使用 C++ 中的 cpprestsdk 发布 json 数据并从本地服务器获取响应
- 获取从网页到 c++ 的 json 响应
- 使用Nlohmann JSON将JSON数据保存在文件中时获取空值
- 如何使用提升包从此 JSON 响应中获取"users_list"
- 使用 boost::asio 读取 JSON 流,获取完整字符串
- 如何将 cpr 的获取响应转换为 json 对象?
- 尝试访问 json dataC++ 时获取空值
- 如何从 nlohmann json 获取对象条目
- 在 qt c++ 中获取 Json 数组中 Qstring 的输出
- C++ :如何从 JSON 获取长整型值并将其转换为 time_point
- 如何获取 json 文件的字符编码类型
- 如何将C++应用程序与节点.js服务器连接以获取 JSON 数据
- 快速JSON库获取没有名称字段的值
- 从 JSON 数组获取天气
- Qt网络访问管理器JSON获取响应