summaryrefslogtreecommitdiff
path: root/json/json.go
blob: 7c84f425f5293b702f65f05b1bc90deee2c29592 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package json

import (
	"errors"

	. "github.com/vektah/goparsify"
)

var (
	value Parser

	_array = Map(And("[", Kleene(&value, ","), "]"), func(n Node) Node {
		ret := []interface{}{}
		for _, child := range n.Children[1].Children {
			ret = append(ret, child.Result)
		}
		return Node{Result: ret}
	})
	properties = Kleene(And(StringLit(`"`), ":", &value), ",")
	_object    = Map(And("{", properties, "}"), func(n Node) Node {
		ret := map[string]interface{}{}

		for _, prop := range n.Children[1].Children {
			ret[prop.Children[0].Result.(string)] = prop.Children[2].Result
		}

		return Node{Result: ret}
	})

	_null   = Bind("null", nil)
	_true   = Bind("true", true)
	_false  = Bind("false", false)
	_string = StringLit(`"`)
	_number = NumberLit()
)

func init() {
	value = Any(_null, _true, _false, _string, _number, _array, _object)
}

func Unmarshal(input string) (interface{}, error) {
	result, remaining, err := ParseString(value, input)

	if err != nil {
		return result, err
	}

	if remaining != "" {
		return result, errors.New("left unparsed: " + remaining)
	}

	return result, err
}