程式語言 - GNU - C/C++ - JSON-C



參考資訊:
https://github.com/json-c/json-c/tree/master

main.c

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <json-c/json.h>

#define JSON_FILE "test.json"
#define JSON_VAL  "myval"

int main(int argc, char **argv)
{
    int val = 0;
    struct json_object *jfile = NULL;

    jfile = json_object_from_file(JSON_FILE);
    if (jfile != NULL) {
        struct json_object *jval = NULL;
        json_object_object_get_ex(jfile, JSON_VAL, &jval);
        val = json_object_get_int(jval);
        printf("old myval: %d\n", val);

        val = 5678;
        json_object_object_add(jfile, JSON_VAL, json_object_new_int(val));
        
        json_object_object_get_ex(jfile, JSON_VAL, &jval);
        val = json_object_get_int(jval);
        printf("new myval: %d\n", val);

        json_object_to_file_ext(JSON_FILE, jfile, JSON_C_TO_STRING_PRETTY);
        json_object_put(jfile);
    }
    return 0;
}

編譯、執行

$ cd
$ git clone https://github.com/json-c/json-c
$ cd json-c
$ mkdir build
$ cd build
$ cmake ..
$ make -j4
$ sudo make install

$ cd
$ echo '{ "myval":1234 }' > test.json

$ gcc main.c -o test -ljson-c
$ LD_LIBRARY_PATH=/usr/local/lib/ ./test
    old myval: 1234
    new myval: 5678

$ cat test.json
    {
      "myval":5678
    }