[英]jansson-change json value in file
我有一個json文件。 並且,文件已成功加載。 但是,我想更改以下值,並保存修改后的json文件。 但是,該值完全不會更改並保存。 我該怎么辦?
來自/home/pi/desktop/test.json
{
"new_one": 1,
"new_two" : "do not",
"new_three" : true
}
到/home/pi/desktop/test.json
{
"new_one": 234,
"new_two" : "do",
"new_three" : false
}
所以我做了
int main()
{
json_t *json;
json_error_t error;
char *pos;
json_t *obj = json_object();
int rc =0 ;
json = json_load_file("./test.json", 0, &error);
if (!json)
{
fprintf(stderr, "process : json error on line %d: %s\n", error.line, error.text);
rc = 1;
}
const char *key;
json_t *value;
void *iter = json_object_iter( json );
while( iter )
{
key = json_object_iter_key(iter);
value = json_object_iter_value(iter);
if(!strcmp(key, "new_one")){
printf("Change Value\n" );
json_object_set(iter, "new_one", json_integer(1234));
}
if(!strcmp(key, "new_three")){
printf("Change Value\n" );
json_object_set(iter, "new_three", json_string("alert"));
}
iter = json_object_iter_next(json, iter);
}
return 0;
}
您缺少對json_dump_file()
的調用,該調用會將修改后的JSON內容保存到文件中。 因此,在while()循環之后,添加以下內容:
rc = json_dump_file(json, "./test.json", 0);
if (rc) {
fprintf(stderr, "cannot save json to file\n");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.