1、修改字典的值
cJSON_SetValuestring(objectItem,value)
//先获取object TempPtr = cJSON_GetObjectItem(TempPtr,"nm"); //修改该object 的值 cJSON_SetValuestring(TempPtr,"guxiang de hai");
2、删除数组里面的值
cJSON_DeleteItemFromArray(Array,index);
// Array 要删除的数组,index 要删除的索引
TempPtrArray = cJSON_GetObjectItem(JsonMain,"items");
cJSON_DeleteItemFromArray(TempPtrArray,0);
3、转为字符串
cJSON_PrintUnformatted(root);
const char *strData = result->data.c_str(); cJSON *root = cJSON_Parse(strData); //修改完root的值后,重新赋值 char* newStr = cJSON_PrintUnformatted(root); result->data = newStr; cJSON_free(newStr); cJSON_Delete(root);
代码:
数据:
{ "tt1":"1234", "tt2":"4321", "items": [ {"nm":"DConHis_recordTime"}, {"nm":"DConHis_GetFlag","va":"1"} ] }
代码:
#include<stdio.h> #include <stdlib.h> #include<unistd.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "lib/cjson/include/cjson/cJSON.h" #include <iostream> static char* cfgPath = "./tt.txt"; int main(int argc, char** argv) { char Buf[4096] = {0}; int bfd = open(cfgPath,O_RDWR); read(bfd,Buf,4095); fprintf(stdout,"\t\t\t\t read json Buf:[%s]",Buf); close(bfd); //解析我们读到的Json字符串 cJSON* JsonMain = cJSON_Parse(Buf); //删除tt1的节点 cJSON_DeleteItemFromObject(JsonMain,"tt1"); //定位到tt2的节点,并修改其值 cJSON* TempPtr = cJSON_GetObjectItem(JsonMain,"tt2"); cJSON* TempPtrArray = NULL; cJSON_SetValuestring(TempPtr,"Now End!"); //定位数组,因为他属于itmes节点,所以找到items节点,它的值就是数组了 TempPtrArray = cJSON_GetObjectItem(JsonMain,"items"); //定位第二个数组,因为索引从0开始计算,所以参数为1 TempPtr = cJSON_GetArrayItem(TempPtrArray,1); //定位到nm节点,并修改nm节点的数值 TempPtr = cJSON_GetObjectItem(TempPtr,"nm"); //更改json 字典的value; cJSON_SetValuestring(TempPtr,"guxiang de hai"); //删除Array 的第一条数据 cJSON_DeleteItemFromArray(TempPtrArray,0); fprintf(stdout,"\nAfter Delete TempPtrmArray index 0 :\n"); char* str1= cJSON_Print(TempPtrArray); fprintf(stdout,"result TempPtrArray :\n%s\n",str1); fprintf(stdout,"reslut JsonMain\n"); str1= cJSON_Print(JsonMain); fprintf(stdout,"\t\t\t\t result json :\n%s\n",str1); //释放资源 cJSON_Delete(JsonMain); cJSON_free(str1); return 0; }
编译:
g++ delete_array.cpp lib/cjson/include/cjson/cJSON.h -L./lib/cjson/lib64/ -lcjson -Wl,-rpath=./lib/cjson/lib64
标签:JsonMain,TempPtrArray,cjson,用法,cJSON,TempPtr,include From: https://www.cnblogs.com/lovychen/p/17918954.html