-
Notifications
You must be signed in to change notification settings - Fork 0
/
ejq.c
119 lines (98 loc) · 2.29 KB
/
ejq.c
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <json-selector.h>
#include <json.h>
char *
read_file(const char *path) {
char *buffer;
int fd = open(path, O_RDONLY, 0666);
if (fd == -1) {
fprintf(stderr, "Cannot access file %s\n", path);
exit(1);
}
long size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
buffer = calloc(sizeof(char), size);
if (read(fd, buffer, size) != size) {
fprintf(stderr, "Failed to read file %s: %m\n", path);
exit(1);
}
close(fd);
return buffer;
}
static void
raw_print(json *obj) {
json *arr = NULL;
if (obj == NULL) {
return;
}
switch (obj->type) {
case JSON_STRING:
printf("%s\n", obj->str);
break;
case JSON_ARRAY:
arr = obj->array;
while (arr) {
raw_print(arr);
arr = arr->next;
}
break;
default:
/* just the normal repr */
printf("%s\n", jsonToString(obj, NULL));
break;
}
}
int
main(int ac, char *av[]) {
int c;
int err = 0;
bool raw = false;
char *expr = NULL;
char *fname = NULL;
json *parsed = NULL;
json *res = NULL;
while ((c = getopt(ac, av, "e:f:r")) != -1) {
switch (c) {
case 'e':
expr = optarg;
break;
case 'f':
fname = optarg;
break;
case 'r':
raw = true;
break;
default:
err++;
}
}
if (err || optind != ac) {
fprintf(stderr, "Usage:\t%s", av[ 0 ]);
fprintf(stderr, " -f <file> [-e <expression>] [-r]\n");
exit(1);
}
parsed = jsonParse(read_file(fname));
if (expr) {
res = jsonSelect(parsed, expr);
/* Selection just returns a pointer to the appropriate place in the
* structure, to easily only output the selected bit we need to throw
* away the key and the following elements (if any).
*/
if (res) {
res->key = NULL;
res->next = NULL;
}
} else {
res = parsed;
}
if (raw) {
raw_print(res);
} else {
printf("%s\n", jsonToString(res, NULL));
}
}