Abhishek Abhishek - 2 years ago 198
C Question

create json object using cJSON.h

I am trying to create JSON object like below but I am not able to add the second item in it e.g:

"CarType": "mercedes",
"carID": "merc123"


and also other items.

I want to create JSON like this:

{
cars: [
{
"CarType": "BMW",
"carID": "bmw123"
},
{
"CarType": "mercedes",
"carID": "merc123"
},
{
"CarType": "volvo",
"carID": "vol123r"
},
{
"CarType": "ford",
"carID": "ford123"
}
]
};


I have tried so far:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"

int main (void){
char field_name[32], value[32], *out;
cJSON *root,*car;

root = cJSON_CreateObject();
car= cJSON_CreateArray();

cJSON_AddItemToObject(root, "CarType", cJSON_CreateString("BMW"));
cJSON_AddItemToObject(root, "carID", cJSON_CreateString("bmw123"));
cJSON_AddItemToArray(car, root);

out = cJSON_Print(car);
printf("%s\n",out);

return 0;
}


My Output is something like this (indentation is exactly as showed here):

[{
"CarType": "BMW",
"carID": "bmw123"
}]

Answer Source

The following code will show you how to use the cJSON functions like cJSON_CreateObject(), cJSON_CreateArray(), cJSON_AddItemToObject() and cJSON_AddItemToArray().

You have to add the cars array to the root object. After that you have to create each car as object containing items which are the CarType and carID. Each car object has to be added to the cars array.

It it also very well documentated with examples here at GitHub.

Code:

#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"

int main()
{
   char *out;
   cJSON *root, *cars, *car;

   /* create root node and array */
   root = cJSON_CreateObject();
   cars = cJSON_CreateArray();

   /* add cars array to root */
   cJSON_AddItemToObject(root, "cars", cars);

   /* add 1st car to cars array */
   cJSON_AddItemToArray(cars, car = cJSON_CreateObject());
   cJSON_AddItemToObject(car, "CarType", cJSON_CreateString("BMW"));
   cJSON_AddItemToObject(car, "carID", cJSON_CreateString("bmw123"));

   /* add 2nd car to cars array */
   cJSON_AddItemToArray(cars, car = cJSON_CreateObject());
   cJSON_AddItemToObject(car, "CarType", cJSON_CreateString("mercedes"));
   cJSON_AddItemToObject(car, "carID", cJSON_CreateString("mercedes123"));

   out = cJSON_Print(root);
   printf("%s\n",out);

   return 0;
}

Output:

{
    "cars": [{
            "CarType":  "BMW",
            "carID":    "bmw123"
        }, {
            "CarType":  "mercedes",
            "carID":    "mercedes123"
        }]
}

This code just add 2 cars to show the usage. In your real application you should do that with C arrays and a for loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download