Skip to content

How do I create a json object from an array of structs? #2266

Answered by nlohmann
m4l490n asked this question in Q&A
Discussion options

You must be logged in to vote

For my_struct_t, you can define a conversion as described in https://github.com/nlohmann/json#arbitrary-types-conversions. The array key for the final result needs to be set explicitly. This is the result:

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

using json = nlohmann::json;

typedef struct { uint8_t a; bool c; float e; } my_struct_t;

void to_json(json& j, const my_struct_t& ms)
{
    j = {ms.a, ms.c, ms.e};
}

int main()
{

    my_struct_t struct_array[] = {
        {1, true,  1.10},
        {2, false, 2.20},
        {3, true,  3.30}
    };

    json result = { {"array", struct_array} };
    std::cout << result << std::endl;
}

Output.

{"array":[[1,true,1.100000023841858],[2,false,2.2000…

Replies: 1 comment 5 replies

Comment options

You must be logged in to vote
5 replies
@m4l490n
Comment options

@nlohmann
Comment options

@m4l490n
Comment options

@nlohmann
Comment options

@m4l490n
Comment options

Answer selected by m4l490n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants