-
-
Notifications
You must be signed in to change notification settings - Fork 6.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Best way to output a vector of a given type to json #1215
Comments
This is described in https://github.com/nlohmann/json#arbitrary-types-conversions: Basically, you need to write a 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 |
Oh nice! |
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: [
{
"x": 1.0,
"y": 2.0,
"z": 3.0
},
{
"x": 3.0,
"y": 4.0,
"z": 5.0
}
]
`` |
Thanks for the post really useful, One question, if this point data comes from a loop and I will like to concatenate it and write it in a file. How can I do it? The output should look like this: [
"segment1",
[
"point",
{
"x": 1,
"y":2
},
"point",
{
"x": 4,
"y": 5.
},
"point",
{
"x": 8,
"y": 3
},
"point",
{
"x": 2,
"y": 2
}
]
"segment2",
[
"point",
{
"x": 1,
"y": 2
},
"point",
{
"x": 3,
"y": 4
},
"point",
{
"x":5 ,
"y": 6
},
"point",
{
"x": 7,
"y": 8
}
]
] Thanks for the help! |
Can you provide more information? What do you mean with concatenate? |
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
The text was updated successfully, but these errors were encountered: