2017-08-06 11:15:07 +02:00
|
|
|
package json
|
|
|
|
|
2017-08-08 12:51:54 +02:00
|
|
|
import "errors"
|
|
|
|
import . "github.com/vektah/goparsify"
|
2017-08-06 11:15:07 +02:00
|
|
|
|
|
|
|
var (
|
2017-08-08 12:51:54 +02:00
|
|
|
_value Parser
|
|
|
|
_null = Bind("null", nil)
|
|
|
|
_true = Bind("true", true)
|
|
|
|
_false = Bind("false", false)
|
|
|
|
_string = StringLit(`"`)
|
|
|
|
_number = NumberLit()
|
2017-08-09 11:35:15 +02:00
|
|
|
_properties = Some(Seq(StringLit(`"`), ":", &_value), ",")
|
2017-08-08 12:51:54 +02:00
|
|
|
|
2017-08-09 11:35:15 +02:00
|
|
|
_array = Map(Seq("[", Some(&_value, ","), "]"), func(n Node) Node {
|
2017-08-07 10:25:23 +02:00
|
|
|
ret := []interface{}{}
|
2017-08-08 15:11:47 +02:00
|
|
|
for _, child := range n.Child[1].Child {
|
2017-08-07 10:25:23 +02:00
|
|
|
ret = append(ret, child.Result)
|
|
|
|
}
|
2017-08-07 13:45:12 +02:00
|
|
|
return Node{Result: ret}
|
2017-08-06 11:15:07 +02:00
|
|
|
})
|
2017-08-08 12:51:54 +02:00
|
|
|
|
2017-08-09 11:35:15 +02:00
|
|
|
_object = Map(Seq("{", _properties, "}"), func(n Node) Node {
|
2017-08-06 11:15:07 +02:00
|
|
|
ret := map[string]interface{}{}
|
|
|
|
|
2017-08-08 15:11:47 +02:00
|
|
|
for _, prop := range n.Child[1].Child {
|
|
|
|
ret[prop.Child[0].Result.(string)] = prop.Child[2].Result
|
2017-08-06 11:15:07 +02:00
|
|
|
}
|
|
|
|
|
2017-08-07 13:45:12 +02:00
|
|
|
return Node{Result: ret}
|
2017-08-06 11:15:07 +02:00
|
|
|
})
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2017-08-08 12:51:54 +02:00
|
|
|
_value = Any(_null, _true, _false, _string, _number, _array, _object)
|
2017-08-06 11:15:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func Unmarshal(input string) (interface{}, error) {
|
2017-08-08 12:51:54 +02:00
|
|
|
result, remaining, err := ParseString(_value, input)
|
2017-08-06 11:15:07 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return result, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if remaining != "" {
|
|
|
|
return result, errors.New("left unparsed: " + remaining)
|
|
|
|
}
|
|
|
|
|
|
|
|
return result, err
|
|
|
|
}
|