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
|
#include <u.h>
#include <libc.h>
#include <json.h>
typedef struct TargetInfo TargetInfo;
struct TargetInfo {
char *name;
int type;
};
void
usage(void)
{
fprint(2, "usage: geoparse [jsonfile]\n");
exits("usage");
}
char *
jsontypestr(int type)
{
char *tab[] = {
[JSONNull] "null",
[JSONBool] "bool",
[JSONNumber] "number",
[JSONString] "string",
[JSONArray] "array",
[JSONObject] "object"
};
return tab[type];
}
TargetInfo ti[] = {
{ "as", JSONString },
{ "city", JSONString },
{ "country", JSONString },
{ "countryCode", JSONString },
{ "isp", JSONString },
{ "lat", JSONNumber },
{ "lon", JSONNumber },
{ "org", JSONString },
{ "query", JSONString },
{ "region", JSONString },
{ "regionName", JSONString },
{ "status", JSONString },
{ "timezone", JSONString },
{ "zip", JSONString }
};
void
main(int argc, char *argv[])
{
char buf[1024];
JSON *obj, *record;
int fd, n;
int i;
if(argc < 2)
fd = 0;
else{
fd = open(argv[1], OREAD);
if(fd < 0)
sysfatal("open: %r");
}
if((n = read(fd, buf, sizeof(buf)-1)) <= 0)
sysfatal("read: %r");
buf[n] = 0;
obj = jsonparse(buf);
if(obj == nil || obj->t != JSONObject)
sysfatal("wrong input");
for(i = 0; i < nelem(ti); i++){
record = jsonbyname(obj, ti[i].name);
if(record == nil)
continue;
if(record->t != ti[i].type)
sysfatal("%s field not a %s",
ti[i].name, jsontypestr(ti[i].type));
if(ti[i].type == JSONString)
print("%s=%s\n", ti[i].name, record->s);
else
print("%s=%g\n", ti[i].name, record->n);
}
jsonfree(obj);
exits(0);
}
|