kgabis/parson

Having a JSON object within a JSON array

Closed this issue · 5 comments

Hello,

I am trying to have something like this printed in a string:

{
"serial": "1234",
"device": "5",
"data": {
"enabled": true,
"fw_version": "12345"
},
"log_data": [
{
"time": 123456,
"sensor1": 12
},
{
"time": 123456,
"sensor2": 12
}
]
}

I used the code provided in this old thread but I can't get around it. It doesn't work

`void serialization_example1(void) {
JSON_Value *root = json_value_init_object();
JSON_Value *arrayRecord = json_value_init_object();
JSON_Object *root_object = json_value_get_object(root);
char *buf_ext = NULL;

json_object_dotset_value(root_object, "log_data", json_value_init_array());

json_object_set_string(root_object, "time", "123456");
json_object_set_number(root_object, "sensor1", "12");

appendArrayRecord(root, "log_data", arrayRecord);
buf_ext = json_serialize_to_string_pretty(root);

puts(buf_ext);

return;
}
`

this is my code but my output looks like:

{
"log_data": [
{}
],
"time": "123456"
"sensor1": 12
}

I would like instead the "time" and "sensor1" to be nested inside log_data, as the original poster was asking. What am I missing in the code?

Many thanks

your code makes the problem. you should use arrayRecord instead of root_object in following code.

json_object_set_string(root_object, "time", "123456");
json_object_set_number(root_object, "sensor1", "12");

arrayRecord is a JsonValue not a JsonObject.
this is the definition of the function JSON_Status json_object_set_string(JSON_Object *object, const char *name, const char *string) so it won't work.

JSON_Object * json_value_get_object (const JSON_Value *value);

Get the object of json value, then insert the key/value into it.

I do have that at the beginning of the code.

JSON_Value *root = json_value_init_object();
JSON_Value *arrayRecord = json_value_init_object();
JSON_Object *root_object = json_value_get_object(root);

What I am missing is how to insert the key value into the array. I tried to follow the example in the other thread but it was kind of incomplete so I can't make it work.
Can you be more specific on how to add the key/value into the array? thanks