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
|
package parser
import (
"fmt"
"strconv"
"strings"
"go.neonxp.dev/json/model"
)
func Parse(json string) (model.Node, error) {
l := newLexer(json)
go l.Run(initJson)
n, err := parse(l.Output)
if err != nil {
return nil, err
}
return model.NewNode(n), nil
}
func parse(ch chan lexem) (any, error) {
prefix := <-ch
switch prefix.Type {
case lObjectStart:
return parseObject(ch)
case lArrayStart:
return parseArray(ch)
case lString:
return strings.Trim(prefix.Value, `"`), nil
case lNumber:
num, err := strconv.ParseFloat(prefix.Value, 64)
if err != nil {
return nil, err
}
return num, nil
case lBoolean:
if strings.ToLower(prefix.Value) == "true" {
return true, nil
}
return false, nil
case lNull:
return nil, nil
}
return nil, fmt.Errorf("ivalid token: '%s' type=%s", prefix.Value, prefix.Type.String())
}
func parseObject(ch chan lexem) (model.NodeObjectValue, error) {
m := model.NodeObjectValue{}
nextKey := ""
for l := range ch {
switch l.Type {
case lObjectKey:
nextKey = strings.Trim(l.Value, `"`)
case lString:
m.Set(nextKey, strings.Trim(l.Value, `"`))
case lNumber:
num, err := strconv.ParseFloat(l.Value, 64)
if err != nil {
return nil, err
}
m.Set(nextKey, num)
case lBoolean:
if strings.ToLower(l.Value) == "true" {
m.Set(nextKey, true)
continue
}
m.Set(nextKey, false)
case lNull:
m.Set(nextKey, nil)
case lObjectStart:
obj, err := parseObject(ch)
if err != nil {
return nil, err
}
m.Set(nextKey, obj)
case lArrayStart:
arr, err := parseArray(ch)
if err != nil {
return nil, err
}
m.Set(nextKey, arr)
case lObjectEnd:
return m, nil
}
}
return nil, fmt.Errorf("unexpected end of object")
}
func parseArray(ch chan lexem) (model.NodeArrayValue, error) {
m := model.NodeArrayValue{}
for l := range ch {
switch l.Type {
case lString:
m = append(m, model.NewNode(strings.Trim(l.Value, `"`)))
case lNumber:
num, err := strconv.ParseFloat(l.Value, 64)
if err != nil {
return nil, err
}
m = append(m, model.NewNode(num))
case lBoolean:
if strings.ToLower(l.Value) == "true" {
m = append(m, model.NewNode(true))
continue
}
m = append(m, model.NewNode(false))
case lNull:
m = append(m, model.NewNode(nil))
case lObjectStart:
obj, err := parseObject(ch)
if err != nil {
return nil, err
}
m = append(m, model.NewNode(obj))
case lArrayStart:
arr, err := parseArray(ch)
if err != nil {
return nil, err
}
m = append(m, model.NewNode(arr))
case lArrayEnd:
return m, nil
}
}
return nil, fmt.Errorf("unexpected end of object")
}
|