yaodav
yaodav

Reputation: 1276

create a valid json file using nlohmann::json

I'm trying to create a valid JSON file that looks like that:

[ { "id": 1, "price": 0, "qty": 0 }, { "id": 1, "price": 1, "qty": 1 }, { "id": 2, "price": 2, "qty": 2 } ]

my current code creates

{ "id": 1, "price": 0, "qty": 0 } { "id": 1, "price": 1, "qty": 1 } { "id": 2, "price": 2, "qty": 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;
}

Upvotes: 1

Views: 2514

Answers (1)

bartop
bartop

Reputation: 10315

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

Upvotes: 3

Related Questions