json讀寫檔案

2021-08-19 13:15:17 字數 2871 閱讀 5143

jsonc 寫配置檔案比較簡單,並且解析配置檔案也比較省事。

寫配置檔案:

[cpp]

view plain

copy

#include 

#include 

#include 

#include 

#include "./inc/json.h"

#define config_file "config.json"

typedef

structa_a_s;  

typedef

struct a_s;  

typedef

struct b_s;  

typedef

struct c_s;  

typedef

struct root_s;   

int main(int argc, char **argv)  

,  },  

.b1 =   

,  .c1 =   

,  };  

root_obj = json_object_new_object();   

new_obj = json_object_new_int(config_struct.root1);  

json_object_object_add(root_obj,"l1_root1",new_obj);  

new_obj = json_object_new_int(config_struct.root2);  

json_object_object_add(root_obj,"l1_root2",new_obj);  

new_obj = json_object_new_string(config_struct.token);  

json_object_object_add(root_obj,"l1_root_token",new_obj);  

json_object *json_obj_a,*json_obj_b,*json_obj_c,*json_obj_a_a1;  

json_obj_a = json_object_new_object();   

json_obj_b = json_object_new_object();   

json_obj_c = json_object_new_object();   

json_obj_a_a1 = json_object_new_object();   

json_object_object_add(json_obj_a_a1,"a_a1_len3",json_object_new_int(config_struct.a1.a1_1.len3));  

json_object_object_add(json_obj_a_a1,"a_a1_len4",json_object_new_int(config_struct.a1.a1_1.len4));  

json_object_object_add(json_obj_a,"a_name",json_object_new_string(config_struct.a1.name));  

json_object_object_add(json_obj_a,"a_len",json_object_new_int(config_struct.a1.len));  

json_object_object_add(json_obj_a,"a_a1_struct",json_obj_a_a1);  

json_object_object_add(json_obj_b,"b_len",json_object_new_int(config_struct.b1.b_len));  

json_object_object_add(json_obj_b,"b_len3",json_object_new_int(config_struct.b1.b_len3));  

json_object_object_add(json_obj_c,"c_len",json_object_new_int(config_struct.c1.c_len));  

json_object_object_add(json_obj_c,"c_len3",json_object_new_int(config_struct.c1.c_len3));  

json_object_object_add(root_obj,"l1_a1",json_obj_a);  

json_object_object_add(root_obj,"l1_b1",json_obj_b);  

json_object_object_add(root_obj,"l1_c1",json_obj_c);  

json_object_to_file(config_file,root_obj);  

json_object_put(root_obj);  

json_object_put(json_obj_a);  

json_object_put(json_obj_a_a1);  

json_object_put(json_obj_b);  

json_object_put(json_obj_c);  

json_object_put(new_obj);  

return 0;  

}  [cpp]

view plain

copy

寫完的配置檔案如下:  

[html]

view plain

copy   

},  

"l1_b1": ,  

"l1_c1":   

}  符合期望的東西。

json_object_object_add 該動作如果要新增的key已經存在,則修改之,否則才會新增。

所以想要修改配置檔案,直接用add的方法就好了,不要用del+add的方式修改。

php讀寫json檔案

生成乙個php陣列 data array 0 array a orange b banana 1 array 1,2,3,4,5,6 2 array first 5 second third data 3 id 30 data 3 content phperwei31 訪問二維陣列的方法 echo ...

python 讀寫json檔案

以字串的形式進行json讀寫 函式功能 json str json.dumps 要寫入的字典表 將字典表寫入json字串 json data json.loads json str 將json字串讀為字典表 import json json的true,false,null寫法和字典表 true,fa...

C 讀寫Json檔案

本文列舉了三種情況的 並且還會繼續更新 1.已有json檔案,並且了解其中內容,想指定更改某些內容 2.已有json檔案,並且了解其中內容,想讀取它的內容 3.沒有json檔案,想按照自己的想法寫乙個json檔案 例子 我的json檔案為example.json c 110,120,119,911 ...