forked from bbuck/dragon-mud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
81 lines (63 loc) · 1.68 KB
/
json.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package talon
import (
"encoding/json"
"regexp"
)
func init() {
Unmarshalers["J"] = func(bs []byte) (interface{}, error) {
j := &JSON{}
err := j.UnmarshalTalon(bs)
if err != nil {
return nil, err
}
return j.Data, nil
}
}
var jsonRx = regexp.MustCompile(`^J!(.+)$`)
// JSONParseError represents an error parsing a JSON value stored in Neo4j
type JSONParseError string
// Error allows JSONParseError to match the error interface.
func (jpe JSONParseError) Error() string {
return string(jpe)
}
// JSON wraps an interface to provide a means for impelmenting the talon
// marshaling library.
type JSON struct {
Data interface{}
}
// NewJSON returns a pointer to the JSON type as a helper.
func NewJSON(i interface{}) *JSON {
return &JSON{
Data: i,
}
}
// Map returns the data (or nil) that is contained within this JSON value as
// a map[string]interface{}
func (j *JSON) Map() map[string]interface{} {
if m, ok := j.Data.(map[string]interface{}); ok {
return m
}
return nil
}
// Slice returns the data (or nil) that is contained within this JSON value as
// a []interface{}
func (j *JSON) Slice() []interface{} {
if s, ok := j.Data.([]interface{}); ok {
return s
}
return nil
}
// MarshalTalon implements the talon.Marshaler interface for the JSON type.
func (j *JSON) MarshalTalon() ([]byte, error) {
bs, err := json.Marshal(j.Data)
bs = append([]byte{'J', '!'}, bs...)
return bs, err
}
// UnmarshalTalon converts the JSON string back into a go type
func (j *JSON) UnmarshalTalon(bs []byte) error {
vals := jsonRx.FindAllSubmatch(bs, 1)
if len(vals) == 0 {
return JSONParseError("JSON string missing correct format")
}
return json.Unmarshal(vals[0][1], &j.Data)
}