简体   繁体   English

使用 nlohmann::json 创建一个有效的 json 文件

[英]create a valid json file using nlohmann::json

I'm trying to create a valid JSON file that looks like that:我正在尝试创建一个有效的 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, "数量": 2 } ]

my current code creates我当前的代码创建

{ "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 , "数量": 2 }

this is the code:这是代码:

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

Just use json::array :只需使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM