0

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;
}
yaodav
  • 1,126
  • 12
  • 34
  • Well, you are creating 3 objects and then printing the objects separately to the file. What you want to do is create one array in you json object, add all 3 object to that array then print it to the file. – super Mar 31 '20 at 09:39

1 Answers1

2

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;
}
bartop
  • 9,971
  • 1
  • 23
  • 54