create json object using cJSON.h

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.

Edit #1:

As @JonnySchubert pointed out, it's necessary to free allocated ressources. But it's enough to free the root node in this case, because adding an item to an array or object transfers it's ownership. In other words: freeing the root node will cause freeing all nodes under root also. From the GitHub ressource I linked above:

For every value type there is a cJSON_Create... function that can be used to create an item of that type. All of these will allocate a cJSON struct that can later be deleted with cJSON_Delete. Note that you have to delete them at some point, otherwise you will get a memory leak. Important: If you have added an item to an array or an object already, you mustn't delete it with cJSON_Delete. Adding it to an array or object transfers its ownership so that when that array or object is deleted, it gets deleted as well.

Edit #2:

@lsalamon mentioned that you have to free the return value of cJSON_Print, see here on SO for example and the documentation.

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"));

   /* print everything */
   out = cJSON_Print(root);
   printf("%s\n", out);
   free(out);

   /* free all objects under root and root itself */
   cJSON_Delete(root)

   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.

Tags:

C

Json

Cjson