Repository navigation
Expand file tree
/
Copy pathjson_gron.awk
More file actions
57 lines (49 loc) · 2.13 KB
/
Copy pathjson_gron.awk
File metadata and controls
57 lines (49 loc) · 2.13 KB
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
BEGIN {
split("", Asm); split("", LineNums)
while (getline > 0) {
if ((Instr = trim($0))!="") { Asm[AsmLen++] = Instr; LineNums[AsmLen] = NR }
}
split("",Stack); split("",PathStack)
Depth = 0
for (i=0; i<AsmLen; i++) {
if (isComplex(Instr = Asm[i])) { p("object"==Instr?"{}":"[]")
Stack[++Depth]=Instr
if (inArr()) { PathStack[Depth]=0 } }
else if (isSingle(Instr)) { p(Instr); incArrIdx() }
else if (isEnd(Instr)) { Depth--; incArrIdx() }
else if ("key" == Instr) { PathStack[Depth]=Asm[++i]; }
else if ("number"==Instr || "string"==Instr) { p(Asm[++i]); incArrIdx() }
else { print "Error at " FILENAME ":" LineNums[i] ": " Instr; exit 1 }
}
}
function isSingle(s) { return "true"==s || "false"==s || "null"==s }
function isComplex(s) { return "object"==s || "array"==s }
function inArr() { return "array"==Stack[Depth] }
function isEnd(s) { return "end_object"==s || "end_array"==s }
function incArrIdx() { if (inArr()) PathStack[Depth]++ }
function p(v, row,i,by_idx,segment,segment_unq) {
row="json"
for(i=1; i<=Depth; i++) {
segment = PathStack[i]
segment_unq = stringUnquote(segment)
# by_idx = "array"==Stack[i] || segment_unq !~ /^[[:alpha:]$_][[:alnum:]$_]*$/ # fails for mawk<=1.3.3
by_idx = "array"==Stack[i] || segment_unq !~ /^[a-zA-Z$_][a-zA-Z0-9$_]*$/
row= row (i==0||by_idx?"":".") (by_idx ? "[" segment "]" : segment_unq)
}
row=row "=" v # ";"
print row
}
function stringUnquote(text, len)
{
len = length(text)
text = len == 2 ? "" : substr(text, 2, len-2)
gsub(/\\\\/, "\\", text)
gsub(/\\"/, "\"", text)
gsub(/\\b/, "\b", text)
gsub(/\\f/, "\f", text)
gsub(/\\n/, "\n", text)
gsub(/\\r/, "\r", text)
gsub(/\\t/, "\t", text)
return text
}
function trim(s) { sub(/^[ \t\r\n]+/, "", s); sub(/[ \t\r\n]+$/, "", s); return s; }