Ronaldinho
Ronaldinho

Reputation: 459

How to write a vector of structs to json file?

Basically, this question is inverse to this one.

I want to write a vector of structs

struct Test {
  std::string Name;
  std::string Val;
};

into a file:

[
  {
    "Name": "test",
    "Val": "test_val"
  },
  {
    "Name": "test2",
    "Val": "test_val2"
  }
]

What I have so far:

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>
#include <nlohmann/json.hpp>
using nlohmann::json;

struct Test {
  std::string Name;
  std::string Val;
};

void to_json(json& j, const Test&  t)
{
    j = json{ {"Name", t.Name}, {"Val", t.Val} };
}

int main(){
    Test t1{"Max", "value1"};
    Test t2{"Kai", "value2"};

    json j1 = t1;
    json j2 = t2;

    std::ofstream o("test_out.json");
    o << std::setw(4) << j1 << std::endl;
    o << std::setw(4) << j2 << std::endl;

    return 0;
}

which gives me:

{
    "Name": "Max",
    "Val": "value1"
}
{
    "Name": "Kai",
    "Val": "value2"
}

What am I missing here?

Upvotes: 3

Views: 2277

Answers (1)

Ronaldinho
Ronaldinho

Reputation: 459

Thanks to Thomas' hint in the comments, I got it working:

int main(){
    Test t1{"Max", "value1"};
    Test t2{"Kai", "value2"};

    json j;
    j.push_back(t1);
    j.push_back(t2);

    std::ofstream o("test_out.json");
    o << std::setw(4) << j << std::endl;
    
    return 0;
}

gives

[
  {
    "Name": "test",
    "Val": "test_val"
  },
  {
    "Name": "test2",
    "Val": "test_val2"
  }
]

Upvotes: 4

Related Questions