forked from dop251/jsonx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterface.go
More file actions
89 lines (76 loc) · 2.1 KB
/
interface.go
File metadata and controls
89 lines (76 loc) · 2.1 KB
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
82
83
84
85
86
87
88
89
package jsonx
// A SyntaxError is a description of a JSON syntax error.
type SyntaxError struct {
msg string // description of error
Offset int // error occurred after reading Offset bytes
}
func (e *SyntaxError) Error() string { return e.msg }
// ExtraDataError is returned when a non-space data was found after parsing the top-level value.
// Offset contains the position of the first byte.
type ExtraDataError struct {
Offset int
}
func (e *ExtraDataError) Error() string { return "Extra data after top-level value" }
// Predefined errors
var (
ErrUnexpectedEOF = &SyntaxError{"unexpected end of JSON input", -1}
ErrInvalidHexEscape = &SyntaxError{"invalid hexadecimal escape sequence", -1}
ErrStringEscape = &SyntaxError{"encountered an invalid escape sequence in a string", -1}
)
// ValueType identifies the type of a parsed value.
type ValueType int
func (v ValueType) String() string {
return types[v]
}
const (
Null ValueType = iota
Bool
String
Number
Object
Array
Unknown
)
var types = map[ValueType]string{
Null: "null",
Bool: "boolean",
String: "string",
Number: "number",
Object: "object",
Array: "array",
Unknown: "unknown",
}
// Type returns the JSON-type of the given value
func Type(v interface{}) ValueType {
t := Unknown
switch v.(type) {
case nil:
t = Null
case bool:
t = Bool
case string:
t = String
case float64:
t = Number
case []interface{}:
t = Array
case map[string]interface{}:
t = Object
}
return t
}
// Decode parses the JSON-encoded data and returns an interface value.
// Equivalent of NewDecoder(data).Decode()
func Decode(data []byte) (interface{}, error) {
return NewDecoder(data).Decode()
}
// DecodeObject is the same as Decode but it returns map[string]interface{}.
// Equivalent of NewDecoder(data).DecodeObject()
func DecodeObject(data []byte) (map[string]interface{}, error) {
return NewDecoder(data).DecodeObject()
}
// DecodeArray is the same as Decode but it returns []interface{}.
// Equivalent of NewDecoder(data).DecodeArray()
func DecodeArray(data []byte) ([]interface{}, error) {
return NewDecoder(data).DecodeArray()
}