Mahamutha M
Mahamutha M

Reputation: 1287

How to add json object in an array?

My target is to append dictionaries in a list(i.e., in python) and now, I need similar operation in C language. How to achieve that?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <jansson.h>


int main()
{
    char* rfid_json_dict = NULL;
    json_t *root = json_object();
    json_t *json_arr = json_array();

    char id[] ="1";
    char value[] =  "D0D0-0000-0000-0000-0001-A431";


    json_object_set_new( root, "id", json_string(id) );
    json_object_set_new( root, "value", json_string(value) );
    rfid_json_dict = json_dumps(root, 0);
    printf("JSON:::%s\n",rfid_json_dict );
}

I have constructed a Json in C i.e.,

JSON:::{"id": "1", "value": "D0D0-0000-0000-0000-0001-A431"}

and How to add this in an array?

Suggestion - 1

As per the suggestion of kjhf, added the below lines with the above give example,

char *buf;
json_array_append( json_arr, root );

buf = json_dumps(json_arr ,0);
printf("JSON:::%s\n",buf );

I can able to achieve the desired result,

JSON:::[{"id": "1", "value": "D0D0-0000-0000-0000-0001-A431"}]

Upvotes: 0

Views: 897

Answers (1)

Slate
Slate

Reputation: 3704

The jansson library comes with a tutorial page and documentation for the json_array.

You're looking for either json_array_set(json_t *array, size_t index, json_t *value) or json_array_append(json_t *array, json_t *value).

Upvotes: 1

Related Questions