fx/pkg/json/parse.go

87 lines
1.5 KiB
Go
Raw Normal View History

2022-04-17 20:57:12 +00:00
package json
2022-03-11 15:15:24 +00:00
import (
"encoding/json"
2022-04-17 20:57:12 +00:00
. "github.com/antonmedv/fx/pkg/dict"
2022-03-11 15:15:24 +00:00
)
2022-04-17 20:57:12 +00:00
func Parse(dec *json.Decoder) (interface{}, error) {
2022-03-11 15:15:24 +00:00
token, err := dec.Token()
if err != nil {
return nil, err
}
if delim, ok := token.(json.Delim); ok {
switch delim {
case '{':
return decodeDict(dec)
case '[':
return decodeArray(dec)
}
}
return token, nil
}
2022-04-17 20:57:12 +00:00
func decodeDict(dec *json.Decoder) (*Dict, error) {
d := NewDict()
2022-03-11 15:15:24 +00:00
for {
token, err := dec.Token()
if err != nil {
return nil, err
}
if delim, ok := token.(json.Delim); ok && delim == '}' {
return d, nil
}
key := token.(string)
token, err = dec.Token()
if err != nil {
return nil, err
}
var value interface{} = token
if delim, ok := token.(json.Delim); ok {
switch delim {
case '{':
value, err = decodeDict(dec)
if err != nil {
return nil, err
}
case '[':
value, err = decodeArray(dec)
if err != nil {
return nil, err
}
}
}
2022-04-17 20:57:12 +00:00
d.Set(key, value)
2022-03-11 15:15:24 +00:00
}
}
func decodeArray(dec *json.Decoder) ([]interface{}, error) {
2022-04-17 20:57:12 +00:00
slice := make(Array, 0)
2022-03-11 15:15:24 +00:00
for index := 0; ; index++ {
token, err := dec.Token()
if err != nil {
return nil, err
}
if delim, ok := token.(json.Delim); ok {
switch delim {
case '{':
value, err := decodeDict(dec)
if err != nil {
return nil, err
}
slice = append(slice, value)
case '[':
value, err := decodeArray(dec)
if err != nil {
return nil, err
}
slice = append(slice, value)
case ']':
return slice, nil
}
continue
}
slice = append(slice, token)
}
}