cJSON is a very nice lib, simple and neat, but one need to understand some things:
cJSON_GetObjectItem(command,"param1")->valuestring
is a char *
, after parsing in this example.
Since you replace it with "new value 1"
, being a const char *
, so when deleting the jsonMsg
, the delete command tries to free that const char *
, resulting in a segmentation fault.
there are a couple of approaches:
char* jsonStr = "{ \"command\" : { \"param1\": \"value1\", \"param2\": \"value2\" } }";
cJSON *jsonMsg = cJSON_Parse(jsonStr);
cJSON *command = CJSON_GetObjectItem(jsonMsg, "command");
till here alright,
then one simple command:
cJSON_ReplaceItemInObject(command,"param1", cJSON_CreateString("new value 1"));
and Finish :
cJSON_Print(jsonMsg);
cJSON_Delete(jsonMsg);
Or
cJSON_DeleteItemFromObject(command,"param1");
cJSON_AddItemToObject(command,"param1",cJSON_CreateString("new value 1"));
Or
If you insist on manually manipulating, ok:
free(cJSON_GetObjectItem(command,"param1")->value string);
cJSON_GetObjectItem(command,"param1")->valuestring=strdup("new value 1");
but if you manipulate manually, one should check the type cJSON_IsReference
before trying to free, secondly the strdup
will allocate new memory to copy the "new value 1" in.