Search code examples
c++jsonnlohmann-json

JSON to an array of structs in nlohmann json lib


I recently asked this question about converting an array of objects into a vector of structs. I want to do the same thing, but rather vectors I want an array. For example

[
  {
    "Name": "Test",
    "Val": "TestVal"
  },
  {
    "Name": "Test2",
    "Val": "TestVal2"
  }
]

And want an array of of these structs:

struct Test {
  string Name;
  string Val;
};

How can this be possible? I am new to c++ so if I am doing anything wrong please say so.


Solution

  • The easiest thing to do is use, wherever you can, std::array instead of C arrays. std::array is a C++ analogue to plain arrays that adds all the nice stuff from std::vector like size() and iterators. You can also return them from functions, unlike C arrays.

    nlohmann also supports it automatically:

    auto parsed = json.get<std::array<Test, 2>>();
    

    Not sure about the library's support for plain ol' C arrays. But you can write a helper function with a little template magic:

    template <typename T, size_t N>
    void from_json(const nlohmann::json& j, T (&t)[N]) {
        if (j.size() != N) {
            throw std::runtime_error("JSON array size is different than expected");
        }
        size_t index = 0;
        for (auto& item : j) {
            from_json(item, t[index++]);
        }
    }
    

    usage:

    Test my_array[N];
    from_json(json, my_array);
    

    Demo: https://godbolt.org/z/-jDTdj