1

I have a json file. And, the file is successfully loaded. but, i would like to change the value such as below and save the json file with the modification. But, the value is not changed and saved at all. How could i do?

from /home/pi/desktop/test.json

{
"new_one": 1,
"new_two" : "do not",
"new_three" : true
}

to /home/pi/desktop/test.json

{
"new_one": 234,
"new_two" : "do",
"new_three" : false
}

So, i did

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;
}
nayang
  • 157
  • 1
  • 14
  • 1
    json object returned by json_load_file() is completely in RAM memory, and does not contain any association to the file any more. So all changes to json object are made to memory only (not to the file). You need to write modified json object to a file. So, Lavra's answer is correct. – SKi Oct 29 '18 at 11:05
  • this is what i need thanks – nayang Oct 30 '18 at 00:07
  • Pretty sure you should be using json_object_set_new - this code has a memory leak using json_object_set on an anonymous object – Chris Mar 23 '23 at 03:51

1 Answers1

3

You are missing a call to json_dump_file(), which will save your modified JSON contents to file. So, after your while() loop, add this:

rc = json_dump_file(json, "./test.json", 0);
if (rc) {
    fprintf(stderr, "cannot save json to file\n");
}
Francesco Lavra
  • 809
  • 6
  • 16