-
I have been reading the documentation and experimenting with some examples and I can't get what I need. I need to create a JSON object that will be an array in which each element consists of the values of a structure. I have the following structure:
And I have an array of 3 these structures with different values:
I then need to create a JSON of all this with the form:
But I'm not sure exactly how to do this since there is not an example of such a case. Could someone please explain how to achieve this or point me to the section(s) where can I see this in the documentation? Thanks! I appreciate the help! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
For #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.200000047683716],[3,true,3.299999952316284]]} Note:
|
Beta Was this translation helpful? Give feedback.
For
my_struct_t
, you can define a conversion as described in https://github.com/nlohmann/json#arbitrary-types-conversions. Thearray
key for the final result needs to be set explicitly. This is the result:Output.