Core

/app/util/json.go (1.7 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
package util

import (
"bytes"
"encoding/json"
"io"

jsoniter "github.com/json-iterator/go"
)

var jsoniterParser = jsoniter.Config{EscapeHTML: false, SortMapKeys: true, ValidateJsonRawMessage: true}.Froze()

func ToJSON(x any) string {
return string(ToJSONBytes(x, true))
}

func ToJSONCompact(x any) string {
return string(ToJSONBytes(x, false))
}

func ToJSONBytes(x any, indent bool) []byte {
if indent {
bts := &bytes.Buffer{}
enc := json.NewEncoder(bts)
if indent {
enc.SetIndent("", " ")
}
enc.SetEscapeHTML(false)
_ = enc.Encode(x) //nolint:errchkjson // no chance of error
return bts.Bytes()
}
b, _ := json.Marshal(x) //nolint:errchkjson // no chance of error
return b
}

func FromJSON(msg json.RawMessage, tgt any) error {
return jsoniterParser.Unmarshal(msg, tgt)
}

func FromJSONString(msg json.RawMessage) (string, error) {
var tgt string
err := jsoniterParser.Unmarshal(msg, &tgt)
return tgt, err
}

func FromJSONMap(msg json.RawMessage) (ValueMap, error) {
var tgt ValueMap
err := jsoniterParser.Unmarshal(msg, &tgt)
return tgt, err
}

func FromJSONInterface(msg json.RawMessage) (any, error) {
var tgt any
err := FromJSON(msg, &tgt)
return tgt, err
}

func FromJSONReader(r io.Reader, tgt any) error {
return json.NewDecoder(r).Decode(tgt)
}

func FromJSONStrict(msg json.RawMessage, tgt any) error {
dec := jsoniterParser.NewDecoder(bytes.NewReader(msg))
dec.DisallowUnknownFields()
return dec.Decode(tgt)
}

func CycleJSON(src any, tgt any) error {
b, _ := jsoniterParser.Marshal(src)
return FromJSON(b, tgt)
}

func JSONToMap(i any) map[string]any {
m := map[string]any{}
_ = CycleJSON(i, &m)
return m
}