7

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"
    }]
Andre Kampling
  • 5,476
  • 2
  • 20
  • 47
Abhishek
  • 133
  • 1
  • 2
  • 9
  • 8
    and what is the question...? – haccks Aug 16 '17 at 08:51
  • 4
    Welcome to StackOverflow. Unfortunately this is neither a tutorial site nor web search replacement. We can help solve [certain problems](https://stackoverflow.com/help/on-topic), but it's **your** job to [put some efforts](http://meta.stackoverflow.com/questions/261592) in the first place, incl. elementary [(re)search](https://google.com/) – Marcin Orlowski Aug 16 '17 at 08:51
  • Edit your question to show us what you have tried and what the actual problem is. – Andre Kampling Aug 16 '17 at 08:54
  • 1
    And what is the problem/output? – Andre Kampling Aug 16 '17 at 09:02
  • Marcin Orlowski - for your info i am putting effort before asking the question & after posting it until i got the answer. and thanks for letting me know that this is not the tutorial site.by the way i got the answer . – Abhishek Aug 16 '17 at 09:58

3 Answers3

16

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.

Andre Kampling
  • 5,476
  • 2
  • 20
  • 47
1

If the json string is fixed you could simply use cJSON_Parse function, to do that you need to have the char* to it :

   const char* const json_string = 
"{ \
  \"cars\": [\
    {\
      \"CarType\": \"BMW\",\
      \"carID\": \"bmw123\"\
    },\
    {\
      \"CarType\": \"mercedes\",\
      \"carID\": \"merc123\"\
    },\
    {\
      \"CarType\": \"volvo\",\
      \"carID\": \"vol123r\"\
    },\
    {\
      \"CarType\": \"ford\",\
      \"carID\": \"ford123\"\
    }\
  ]\
}\
";

   cJSON * root = cJSON_Parse(json_string);  /* Play with root */

   //char *rendered = cJSON_Print(root);

Updated as per request , when input array is not fixed:

   const char* const carType[] ={"BMW", "Mercides", "Audi", "Farari"}; 
   const char* const carID[]  ={"bmw11", "m22", "a33", "f44"} ;

   size_t max_size = 4;
   cJSON *root,*car;

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

   for( size_t i = 0; i < max_size; ++i )
   {
      cJSON* item  = cJSON_CreateObject(); 
      cJSON_AddItemToObject(item, "CarType", cJSON_CreateString( carType[i] ));
      cJSON_AddItemToObject(item, "carID", cJSON_CreateString(carID[i]));

      cJSON_AddItemToArray(car, item);
   }


   cJSON_AddItemToObject( root, "cars", car );
P0W
  • 46,614
  • 9
  • 72
  • 119
0

Another solution i got -

#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("bmws123"));
    cJSON_AddItemToArray(car, root);

    root=NULL;
    root  = cJSON_CreateObject();

    cJSON_AddItemToObject(root, "CarType", cJSON_CreateString("Mercedies"));
    cJSON_AddItemToObject(root, "carID", cJSON_CreateString("mer123"));
    cJSON_AddItemToArray(car, root);



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


    return 0;
}
Abhishek
  • 133
  • 1
  • 2
  • 9
  • Yes would work but names are wrong in usage here as you using `root` **not** as root object. Further you have just an array `car` without a root object. – Andre Kampling Aug 16 '17 at 09:53