-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathencoding_json.go
More file actions
84 lines (73 loc) · 1.74 KB
/
encoding_json.go
File metadata and controls
84 lines (73 loc) · 1.74 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
package stable
import (
"encoding/json"
"errors"
"sort"
)
var (
// ErrNullJSON error null json
ErrNullJSON error = errors.New("'stable' error. null json")
)
// jsonSwitch switch for array or object type json
func jsonSwitch(data []byte) (*STable, error) {
if len(data) == 0 {
return nil, ErrNullJSON
}
if data[0] == '[' {
return encodeJSONArray(data)
}
return encodeJSON(data)
}
func encodeJSON(j []byte) (*STable, error) {
var jj map[string]interface{}
err := json.Unmarshal(j, &jj)
if err != nil {
return nil, err
}
return encodeMap(jj)
}
func encodeJSONArray(j []byte) (*STable, error) {
var jj []map[string]interface{}
err := json.Unmarshal(j, &jj)
if err != nil {
return nil, err
}
if len(jj) == 0 {
return nil, ErrNullJSON
}
return encodeMapArray(jj)
}
func encodeMap(m map[string]interface{}) (*STable, error) {
table := New("json")
table.AddFields("key", "value")
fieldNames := make([]string, 0, len(m))
for k := range m {
fieldNames = append(fieldNames, k)
}
sort.Slice(fieldNames, func(i, j int) bool { return fieldNames[i] < fieldNames[j] })
for i := 0; i < len(fieldNames); i++ {
key := fieldNames[i]
value := m[key]
table.Row(key, value)
}
return table, nil
}
func encodeMapArray(m []map[string]interface{}) (*STable, error) {
f := m[0]
fieldNames := make([]string, 0, len(f))
for k := range f {
fieldNames = append(fieldNames, k)
}
sort.Slice(fieldNames, func(i, j int) bool { return fieldNames[i] < fieldNames[j] })
table := New("json")
table.AddFields(fieldNames...)
for _, j := range m {
values := make([]interface{}, 0, len(fieldNames))
for i := 0; i < len(fieldNames); i++ {
field := fieldNames[i]
values = append(values, j[field])
}
table.Row(values...)
}
return table, nil
}