-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd.c
More file actions
35 lines (30 loc) · 1018 Bytes
/
add.c
File metadata and controls
35 lines (30 loc) · 1018 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <json-c/json.h>
#include <stdio.h>
int main() {
// Write
struct json_object *root = json_object_new_object();
json_object_object_add(root, "name", json_object_new_string("Bob"));
json_object_object_add(root, "age", json_object_new_int(25));
FILE *fp = fopen("data.json", "w");
fputs(json_object_to_json_string_ext(root, JSON_C_TO_STRING_PRETTY), fp);
fclose(fp);
json_object_put(root);
// Read
fp = fopen("data.json", "r");
fseek(fp, 0, SEEK_END);
long len = ftell(fp);
rewind(fp);
char *data = malloc(len + 1);
fread(data, 1, len, fp);
data[len] = '\0';
fclose(fp);
struct json_object *parsed = json_tokener_parse(data);
free(data);
struct json_object *name, *age;
json_object_object_get_ex(parsed, "name", &name);
json_object_object_get_ex(parsed, "age", &age);
printf("Name: %s\n", json_object_get_string(name));
printf("Age: %d\n", json_object_get_int(age));
json_object_put(parsed);
return 0;
}