-
Notifications
You must be signed in to change notification settings - Fork 85
/
json.go
62 lines (55 loc) · 1.37 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
package notionapi
import (
"encoding/json"
jsoniter "github.com/json-iterator/go"
"github.com/tidwall/pretty"
)
var (
PrettyPrintJS = PrettyPrintJSJsonit
jsonit = jsoniter.ConfigCompatibleWithStandardLibrary
prettyOpts = pretty.Options{
Width: 80,
Prefix: "",
Indent: " ",
// sorting keys only slightly slower
SortKeys: true,
}
)
// TODO: doesn't work with some of Notion json responses?
// pretty-print if valid JSON. If not, return unchanged
// about 4x faster than naive version using json.Unmarshal() + json.Marshal()
func PrettyPrintJSJsonit(js []byte) []byte {
if !jsonit.Valid(js) {
return js
}
return pretty.PrettyOptions(js, &prettyOpts)
}
// pretty-print if valid JSON. If not, return unchanged
// about 4x faster than naive version using json.Unmarshal() + json.Marshal()
func PrettyPrintJSStd(js []byte) []byte {
var m map[string]interface{}
err := json.Unmarshal(js, &m)
if err != nil {
return js
}
d, err := json.MarshalIndent(m, "", " ")
if err != nil {
return js
}
return d
}
func jsonUnmarshalFromMap(m map[string]interface{}, v interface{}) error {
d, err := jsonit.Marshal(m)
if err != nil {
return err
}
return json.Unmarshal(d, v)
}
func jsonGetMap(m map[string]interface{}, key string) map[string]interface{} {
if v, ok := m[key]; ok {
if m, ok := v.(map[string]interface{}); ok {
return m
}
}
return nil
}