2

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!" } ] }

Ali Hatami
  • 144
  • 10
  • Does this answer your question? [cJSON c++ - add item object](https://stackoverflow.com/questions/43272300/cjson-c-add-item-object) – ralf htp Jan 09 '20 at 22:53

1 Answers1

2

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;
}
hko
  • 548
  • 2
  • 19