Json: Best way to output a vector of a given type to json

Created on 24 Aug 2018  路  5Comments  路  Source: nlohmann/json

This is not a feature request, but more a question.

I'll give you my exact use case so it is easy to understand.
I have a 3D point struct:
struct Point { float x, y, z; };

I have a very large vector of this points and would like to output them to json with each point in the format: { "x": x, "y": y, "z": z}

I can easily do it by creating an array and using emplace_back. It works, but it is slow because the current API doesn't provide a resize or a reserve like std::vector does.

Is there a way to create my json as fast as possible?
Thank you

question proposed fix

Most helpful comment

For reference:

#include <iostream>
#include <iomanip>
#include "json.hpp"

using json = nlohmann::json;

struct Point { float x, y, z; };

void to_json(json& j, const Point& p)
{
    j = {{"x", p.x}, {"y", p.y}, {"z", p.z}};
}

int main(int argc, const char **argv) {
    Point p1 = {1,2,3};
    Point p2 = {3,4,5};

    std::vector<Point> v = {p1, p2};
    json j = v;

    std::cout << std::setw(2) << j << std::endl;
}

Output:

`js [ { "x": 1.0, "y": 2.0, "z": 3.0 }, { "x": 3.0, "y": 4.0, "z": 5.0 } ]

All 5 comments

This is described in https://github.com/nlohmann/json#arbitrary-types-conversions: Basically, you need to write a void to_json(json& j, const Point& p) function in the namespace of Point where you set j to your preference, e.g. j = {{"x", p.x}, {"y", p.y}, {"z", p.z}};. Then you can write

Point p {1,2,3};
json j = p;

How do I convert the vector of Point, then? Still with successive emplace_back?

Once you define how Point -> json works, then a std:.vector<Point> will be automatically translated to an array.

Oh nice!
Thank you for your quick reply!

For reference:

#include <iostream>
#include <iomanip>
#include "json.hpp"

using json = nlohmann::json;

struct Point { float x, y, z; };

void to_json(json& j, const Point& p)
{
    j = {{"x", p.x}, {"y", p.y}, {"z", p.z}};
}

int main(int argc, const char **argv) {
    Point p1 = {1,2,3};
    Point p2 = {3,4,5};

    std::vector<Point> v = {p1, p2};
    json j = v;

    std::cout << std::setw(2) << j << std::endl;
}

Output:

`js [ { "x": 1.0, "y": 2.0, "z": 3.0 }, { "x": 3.0, "y": 4.0, "z": 5.0 } ]

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zhishupp picture zhishupp  路  4Comments

asmaloney picture asmaloney  路  4Comments

edi9999 picture edi9999  路  3Comments

koemeet picture koemeet  路  4Comments

alienzj picture alienzj  路  4Comments