使用 nlohmann::json 创建一个有效的 json 文件
create a valid json file using nlohmann::json
我正在尝试创建一个有效的 JSON 文件,如下所示:
[ { "id": 1, "price": 0, "qty": 0 }, { "id": 1, "price": 1,
"qty": 1 }, { "id": 2, "price": 2, "qty": 2 } ]
我当前的代码创建
{ "id": 1, "price": 0, "qty": 0 } { "id": 1, "price": 1, "qty":
1 } { "id": 2, "price": 2, "qty": 2 }
这是代码:
int main() {
std::ofstream f;
f.open("test.json",std::ios_base::trunc |std::ios_base::out);
for(int i =0 ;i < 100 ; i++)
{
json j = {
{"id",i},
{"qty",i},
{"price",i}
};
f << j << "\n";
}
f.close();
return 0;
}
只需使用json::array
:
int main() {
json result = json::array();
for (int i =0; i < 100 ; i++) {
json j = {
{"id",i},
{"qty",i},
{"price",i}
};
result.push_back(j);
}
{
std::ofstream f("test.json",std::ios_base::trunc |std::ios_base::out);
f << result;
}
return 0;
}
我正在尝试创建一个有效的 JSON 文件,如下所示:
[ { "id": 1, "price": 0, "qty": 0 }, { "id": 1, "price": 1, "qty": 1 }, { "id": 2, "price": 2, "qty": 2 } ]
我当前的代码创建
{ "id": 1, "price": 0, "qty": 0 } { "id": 1, "price": 1, "qty": 1 } { "id": 2, "price": 2, "qty": 2 }
这是代码:
int main() {
std::ofstream f;
f.open("test.json",std::ios_base::trunc |std::ios_base::out);
for(int i =0 ;i < 100 ; i++)
{
json j = {
{"id",i},
{"qty",i},
{"price",i}
};
f << j << "\n";
}
f.close();
return 0;
}
只需使用json::array
:
int main() {
json result = json::array();
for (int i =0; i < 100 ; i++) {
json j = {
{"id",i},
{"qty",i},
{"price",i}
};
result.push_back(j);
}
{
std::ofstream f("test.json",std::ios_base::trunc |std::ios_base::out);
f << result;
}
return 0;
}