-
Notifications
You must be signed in to change notification settings - Fork 536
/
value.go
47 lines (43 loc) · 1.16 KB
/
value.go
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
package lorca
import "encoding/json"
// Value is a generic type of a JSON value (primitive, object, array) and
// optionally an error value.
type Value interface {
Err() error
To(interface{}) error
Float() float32
Int() int
String() string
Bool() bool
Object() map[string]Value
Array() []Value
Bytes() []byte
}
type value struct {
err error
raw json.RawMessage
}
func (v value) Err() error { return v.err }
func (v value) Bytes() []byte { return v.raw }
func (v value) To(x interface{}) error { return json.Unmarshal(v.raw, x) }
func (v value) Float() (f float32) { v.To(&f); return f }
func (v value) Int() (i int) { v.To(&i); return i }
func (v value) String() (s string) { v.To(&s); return s }
func (v value) Bool() (b bool) { v.To(&b); return b }
func (v value) Array() (values []Value) {
array := []json.RawMessage{}
v.To(&array)
for _, el := range array {
values = append(values, value{raw: el})
}
return values
}
func (v value) Object() (object map[string]Value) {
object = map[string]Value{}
kv := map[string]json.RawMessage{}
v.To(&kv)
for k, v := range kv {
object[k] = value{raw: v}
}
return object
}