2017-08-06 11:15:07 +02:00
|
|
|
package json
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
. "github.com/vektah/goparsify"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
value Parser
|
|
|
|
|
2017-08-07 10:25:23 +02:00
|
|
|
_array = Map(And(WS, "[", Kleene(&value, And(WS, ",")), "]"), func(n *Node) *Node {
|
|
|
|
ret := []interface{}{}
|
|
|
|
for _, child := range n.Children[1].Children {
|
|
|
|
ret = append(ret, child.Result)
|
|
|
|
}
|
|
|
|
return &Node{Result: ret}
|
2017-08-06 11:15:07 +02:00
|
|
|
})
|
|
|
|
properties = Kleene(And(WS, String('"'), WS, ":", WS, &value), ",")
|
2017-08-07 10:25:23 +02:00
|
|
|
_object = Map(And(WS, "{", WS, properties, WS, "}"), func(n *Node) *Node {
|
2017-08-06 11:15:07 +02:00
|
|
|
ret := map[string]interface{}{}
|
|
|
|
|
2017-08-07 10:25:23 +02:00
|
|
|
for _, prop := range n.Children[1].Children {
|
|
|
|
ret[prop.Children[0].Token] = prop.Children[2].Result
|
2017-08-06 11:15:07 +02:00
|
|
|
}
|
|
|
|
|
2017-08-07 10:25:23 +02:00
|
|
|
return &Node{Result: ret}
|
2017-08-06 11:15:07 +02:00
|
|
|
})
|
|
|
|
|
2017-08-07 10:25:23 +02:00
|
|
|
_null = Map(And(WS, "null"), func(n *Node) *Node {
|
|
|
|
return &Node{Result: nil}
|
2017-08-06 11:15:07 +02:00
|
|
|
})
|
|
|
|
|
2017-08-07 10:25:23 +02:00
|
|
|
_true = Map(And(WS, "true"), func(n *Node) *Node {
|
|
|
|
return &Node{Result: true}
|
2017-08-06 11:15:07 +02:00
|
|
|
})
|
|
|
|
|
2017-08-07 10:25:23 +02:00
|
|
|
_false = Map(And(WS, "false"), func(n *Node) *Node {
|
|
|
|
return &Node{Result: false}
|
2017-08-06 11:15:07 +02:00
|
|
|
})
|
|
|
|
|
2017-08-07 10:25:23 +02:00
|
|
|
_string = Map(String('"'), func(n *Node) *Node {
|
|
|
|
return &Node{Result: n.Token}
|
|
|
|
})
|
|
|
|
|
|
|
|
Y = Map(And(&value, WS), func(n *Node) *Node {
|
|
|
|
return &Node{Result: n.Children[0].Result}
|
2017-08-06 11:15:07 +02:00
|
|
|
})
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2017-08-07 10:25:23 +02:00
|
|
|
value = Any(_null, _true, _false, _string, _array, _object)
|
2017-08-06 11:15:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func Unmarshal(input string) (interface{}, error) {
|
|
|
|
result, remaining, err := ParseString(Y, input)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return result, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if remaining != "" {
|
|
|
|
return result, errors.New("left unparsed: " + remaining)
|
|
|
|
}
|
|
|
|
|
|
|
|
return result, err
|
|
|
|
}
|