Search code examples
cjsoncjson

How can we add a new item to a parsed JSON with cJSON?


I am programming a server for my client that keeps messages. I keep them in JSON format using cJSON -by Dave Gambler- And save them in a text file. how can I add a new item to my Array after reading the string from file and parsing it? The JSON string is like below :

{ "messages":[ { "sender":"SERVER","message":"Channel Created" } , { "sender":"Will","message":"Hello Buddies!" } ] }


Solution

  • After parsing your json string you need to create a new object that contains your new message and add the object to the existing array.

    #include <stdio.h>
    #include "cJSON.h"
    
    int main()
    {
        cJSON *msg_array, *item;
        cJSON *messages = cJSON_Parse(
            "{ \"messages\":[ \
             { \"sender\":\"SERVER\", \"message\":\"Channel Created\" }, \
             { \"sender\":\"Will\", \"message\":\"Hello Buddies!\" } ] }");
        if (!messages) {
            printf("Error before: [%s]\n", cJSON_GetErrorPtr());
        }
        msg_array = cJSON_GetObjectItem(messages, "messages");
    
        // Create a new array item and add sender and message
        item = cJSON_CreateObject();
        cJSON_AddItemToObject(item, "sender", cJSON_CreateString("new sender"));
        cJSON_AddItemToObject(item, "message", cJSON_CreateString("new message"));
    
        // insert the new message into the existing array
        cJSON_AddItemToArray(msg_array, item);
    
        printf("%s\n", cJSON_Print(messages));
        cJSON_Delete(messages);
    
        return 0;
    }