简体   繁体   中英

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM