json2gostruct.sh - randomcrap - random crap programs of varying quality
(HTM) git clone git://git.codemadness.org/randomcrap
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
json2gostruct.sh (2080B)
---
1 #!/bin/sh
2 # Helper tool to convert JSON example data to a Golang struct (for JSON
3 # unmarshal).It probably needs some manual tweaks to optimize the structure,
4 # this is intended.
5 # Dependencies: awk, json2tsv
6
7 json2tsv | \
8 awk '
9 BEGIN {
10 FS = OFS = "\t";
11 }
12
13 function unescape(s) {
14 return s;
15 }
16
17 function fieldname(s) {
18 match(s, "[^\\.]*$");
19 if (RSTART != -1) {
20 s = substr(s, RSTART, RLENGTH);
21 }
22 gsub("\\[\\]", "", s);
23 return s;
24 }
25
26 function countdepth(s) {
27 depth = 0;
28 len = length(s);
29 for (i = 0; i < len; i++) {
30 c = substr(s, i, 1);
31 if (c == "." || c == "[")
32 depth++;
33 }
34 return depth;
35 }
36
37 function indent(d) {
38 s = "";
39 for (i = 0; i < d; i++) {
40 # if (types[i] == "a")
41 # continue;
42 s = s "\t";
43 }
44 return s;
45 }
46
47 function endstruct() {
48 for (i = prevdepth - 1; i >= depth; i--) {
49 # if (types[i] == "a")
50 # continue;
51 print indent(i) "} `json:\"" jsonfields[i] "\"`"
52 }
53 }
54
55 {
56 jsonfield = fieldname($1);
57 field = tolower(jsonfield);
58
59 depth = countdepth($1);
60 if (depth < prevdepth) {
61 endstruct();
62 } else if (prevdepth == depth && (types[depth] == "o" || types[depth] == "a")) {
63 print indent(depth) "}"; # empty object or array.
64 }
65
66 value = unescape($3);
67 # uppercase first letter.
68 if (length(field) > 0) {
69 field = toupper(substr(field, 1, 1)) tolower(substr(field, 2));
70 }
71
72 jsonfields[depth] = jsonfield;
73 fields[depth] field;
74 types[depth] = $2;
75
76 prevdepth = depth;
77 prevjsonfield = jsonfield;
78 }
79
80 $2 == "o" {
81 # if (depth && types[depth - 1] == "a")
82 # next;
83 print indent(depth) field " struct {";
84 }
85 $2 == "a" {
86 print indent(depth) field " []struct {";
87 }
88 $2 == "n" {
89 match($3, "\\.");
90 if (RSTART != -1) {
91 type = "float64";
92 } else {
93 type = "int64";
94 }
95 print indent(depth) field " " type " `json:\"" jsonfield "\"` // " value;
96 }
97 $2 == "b" {
98 print indent(depth) field " bool `json:\"" jsonfield "\"` // " value;
99 }
100 $2 == "s" {
101 print indent(depth) field " string `json:\"" jsonfield "\"` // \"" value "\"";
102 }
103 $2 == "?" {
104 print indent(depth) field " UNKNOWN_NULL `json:\"" jsonfield "\"` // " value;
105 }
106
107 END {
108 depth = 1;
109 endstruct();
110 }'
111