-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
132 lines (120 loc) · 2.62 KB
/
parser.go
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
120
121
122
123
124
125
126
127
128
129
130
131
132
package parser
import "strings"
const (
insideMap = iota
insideArr
)
type stack []int
// IsEmpty: check if stack is empty
func (s *stack) IsEmpty() bool {
return len(*s) == 0
}
// Push a new value onto the stack
func (s *stack) Push(val int) {
*s = append(*s, val) // Simply append the new value to the end of the stack
}
// Peek the top value on the stack
func (s *stack) Peek() (int, bool) {
if s.IsEmpty() {
return 0, false
} else {
index := len(*s) - 1 // Get the index of the top most element.
element := (*s)[index] // Index into the slice and obtain the element.
return element, true
}
}
// Remove and return top element of stack. Return false if stack is empty.
func (s *stack) Pop() (int, bool) {
if s.IsEmpty() {
return 0, false
} else {
index := len(*s) - 1 // Get the index of the top most element.
element := (*s)[index] // Index into the slice and obtain the element.
*s = (*s)[:index] // Remove it from the stack by slicing it off.
return element, true
}
}
func ToJSON(input string) ([]byte, error) {
var stack stack
var out strings.Builder
keyExpected, valExpected := false, false
i := 0
for i < len(input) {
char := input[i]
if keyExpected {
if char == '}' {
continue
}
out.WriteString(`"`)
for i < len(input) && char != ':' {
out.WriteByte(char)
i++
char = input[i]
}
out.WriteString(`":`)
i++
char = input[i]
keyExpected = false
valExpected = true
}
if valExpected {
if input[i:i+4] == "map[" {
i += 4
out.WriteString("{")
stack.Push(insideMap)
keyExpected = true
continue
}
if input[i] == '[' {
i++
out.WriteString("[")
stack.Push(insideArr)
continue
}
out.WriteString(`"`)
for i < len(input)-1 && char != ' ' && char != ']' {
out.WriteByte(char)
i++
char = input[i]
}
out.WriteString(`"`)
valExpected = false
}
switch char {
case '{', '[':
out.WriteString(`{`)
i++
if input[i] != '}' && input[i] != ']' {
if currLoc, got := stack.Peek(); got && currLoc == insideArr {
valExpected = true
keyExpected = false
} else {
keyExpected = true
}
}
continue
case ' ':
i++
out.WriteString(`, `)
if input[i] != '}' && input[i] != ']' {
if currLoc, got := stack.Peek(); got && currLoc == insideArr {
valExpected = true
keyExpected = false
} else {
keyExpected = true
}
}
continue
case '}', ']':
if currLoc, got := stack.Pop(); got && currLoc == insideArr {
out.WriteString(`]`)
} else {
out.WriteString(`}`)
}
i++
continue
}
i++
}
return []byte(out.String()), nil
}