2017-08-06 11:15:07 +02:00
|
|
|
package json
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
. "github.com/vektah/goparsify"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
value Parser
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
array = Map(And(WS, "[", Kleene(&value, And(WS, ",")), "]"), func(n interface{}) interface{} {
|
|
|
|
return n.([]interface{})[1].([]interface{})
|
2017-08-06 11:15:07 +02:00
|
|
|
})
|
|
|
|
properties = Kleene(And(WS, String('"'), WS, ":", WS, &value), ",")
|
2017-08-06 15:32:10 +02:00
|
|
|
object = Map(And(WS, "{", WS, properties, WS, "}"), func(n interface{}) interface{} {
|
2017-08-06 11:15:07 +02:00
|
|
|
ret := map[string]interface{}{}
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
for _, prop := range n.([]interface{})[1].([]interface{}) {
|
|
|
|
vals := prop.([]interface{})
|
2017-08-06 11:15:07 +02:00
|
|
|
if len(vals) == 3 {
|
|
|
|
ret[vals[0].(string)] = vals[2]
|
|
|
|
} else {
|
|
|
|
ret[vals[0].(string)] = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret
|
|
|
|
})
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
_null = Map(And(WS, "null"), func(n interface{}) interface{} {
|
2017-08-06 11:15:07 +02:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
_true = Map(And(WS, "true"), func(n interface{}) interface{} {
|
2017-08-06 11:15:07 +02:00
|
|
|
return true
|
|
|
|
})
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
_false = Map(And(WS, "false"), func(n interface{}) interface{} {
|
2017-08-06 11:15:07 +02:00
|
|
|
return false
|
|
|
|
})
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
Y = Map(And(&value, WS), func(n interface{}) interface{} {
|
|
|
|
nodes := n.([]interface{})
|
2017-08-06 11:15:07 +02:00
|
|
|
if len(nodes) > 0 {
|
|
|
|
return nodes[0]
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
value = Any(_null, _true, _false, String('"'), array, object)
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|