create json object using cJSON.h

Viewed 15660

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"
    }]
3 Answers
Related