blob: 842ab829f27f74e0886e3f10d30f32074e49ad13 (
plain) (
blame)
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
|
// +build ignore
package main
import (
"fmt"
"github.com/neonxp/unilex"
)
func main() {
testJson := `
{
"key1": "value1",
"key2": {
"key3" : "value 3"
},
"key4": 123.321
}`
l := unilex.New(testJson)
go l.Run(initJson)
for ll := range l.Output {
fmt.Println(ll)
}
}
const (
lObjectStart unilex.LexType = "lObjectStart"
lObjectEnd unilex.LexType = "lObjectEnd"
lObjectKey unilex.LexType = "lObjectKey"
lObjectValueString unilex.LexType = "lObjectValueString"
lObjectValueNumber unilex.LexType = "lObjectValueNumber"
)
func initJson(l *unilex.Lexer) unilex.StateFunc {
ignoreWhiteSpace(l)
switch {
case l.Accept("{"):
l.Emit(lObjectStart)
return stateInObject(true)
case l.Peek() == unilex.EOF:
return nil
}
return l.Errorf("Unknown token: %s", l.Peek())
}
func stateInObject(initial bool) unilex.StateFunc {
return func(l *unilex.Lexer) unilex.StateFunc {
// we in object, so we expect field keys and values
ignoreWhiteSpace(l)
if l.Accept("}") {
l.Emit(lObjectEnd)
if initial {
return initJson
}
ignoreWhiteSpace(l)
l.Accept(",")
ignoreWhiteSpace(l)
return stateInObject(initial)
}
if l.Peek() == unilex.EOF {
return nil
}
if !unilex.ScanQuotedString(l, '"') {
return l.Errorf("Unknown token: %s", l.Peek())
}
l.Emit(lObjectKey)
ignoreWhiteSpace(l)
if !l.Accept(":") {
return l.Errorf("Expected ':'")
}
ignoreWhiteSpace(l)
switch {
case unilex.ScanQuotedString(l, '"'):
l.Emit(lObjectValueString)
ignoreWhiteSpace(l)
l.Accept(",")
l.Ignore()
ignoreWhiteSpace(l)
return stateInObject(initial)
case unilex.ScanNumber(l):
l.Emit(lObjectValueNumber)
ignoreWhiteSpace(l)
l.Accept(",")
l.Ignore()
ignoreWhiteSpace(l)
return stateInObject(initial)
case l.Accept("{"):
l.Emit(lObjectStart)
return stateInObject(false)
}
return l.Errorf("Unknown token")
}
}
func ignoreWhiteSpace(l *unilex.Lexer) {
l.AcceptWhile(" \n\t") //ignore whitespaces
l.Ignore()
}
|