goparsify/json/json.go

43 lines
1.0 KiB
Go
Raw Normal View History

2017-08-06 11:15:07 +02:00
package json
2017-08-10 13:04:14 +02:00
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-13 04:56:46 +02:00
_array = Seq("[", Cut(), Some(&_value, ","), "]").Map(func(n Result) Result {
2017-08-07 10:25:23 +02:00
ret := []interface{}{}
2017-08-10 13:04:14 +02:00
for _, child := range n.Child[2].Child {
2017-08-07 10:25:23 +02:00
ret = append(ret, child.Result)
}
2017-08-09 13:18:14 +02:00
return Result{Result: ret}
2017-08-06 11:15:07 +02:00
})
2017-08-08 12:51:54 +02:00
2017-08-13 04:56:46 +02:00
_object = Seq("{", Cut(), _properties, "}").Map(func(n Result) Result {
2017-08-06 11:15:07 +02:00
ret := map[string]interface{}{}
2017-08-10 13:04:14 +02:00
for _, prop := range n.Child[2].Child {
2017-08-08 15:11:47 +02:00
ret[prop.Child[0].Result.(string)] = prop.Child[2].Result
2017-08-06 11:15:07 +02:00
}
2017-08-09 13:18:14 +02:00
return Result{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
}
2017-08-10 16:10:58 +02:00
// Unmarshall json string into map[string]interface{} or []interface{}
func Unmarshal(input string) (interface{}, error) {
2017-08-10 14:06:08 +02:00
return Run(_value, input, ASCIIWhitespace)
2017-08-06 11:15:07 +02:00
}