json.go 837 Bytes
Newer Older
Vladimir Barsukov's avatar
Vladimir Barsukov committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//go:build !go_json

package zjson

import (
	"encoding/json"
	"unsafe"
)

func ToBytes(obj any) ([]byte, error) {
	return json.Marshal(obj)
}

func ToString(obj any) (string, error) {
Vladimir Barsukov's avatar
lint    
Vladimir Barsukov committed
15
16
17
18
	var err error
	var b []byte

	if b, err = json.Marshal(obj); err != nil {
Vladimir Barsukov's avatar
Vladimir Barsukov committed
19
20
		return "", err
	}
Vladimir Barsukov's avatar
lint    
Vladimir Barsukov committed
21
22

	return *(*string)(unsafe.Pointer(&b)), nil
Vladimir Barsukov's avatar
Vladimir Barsukov committed
23
24
25
}

func ToStringSafe(obj any) (string, error) {
Vladimir Barsukov's avatar
lint    
Vladimir Barsukov committed
26
27
28
29
	var err error
	var b []byte

	if b, err = json.Marshal(obj); err != nil {
Vladimir Barsukov's avatar
Vladimir Barsukov committed
30
31
		return "", err
	}
Vladimir Barsukov's avatar
lint    
Vladimir Barsukov committed
32
33

	return string(b), err
Vladimir Barsukov's avatar
Vladimir Barsukov committed
34
35
36
37
}

func MustBytes(obj any) []byte {
	b, _ := ToBytes(obj)
Vladimir Barsukov's avatar
lint    
Vladimir Barsukov committed
38

Vladimir Barsukov's avatar
Vladimir Barsukov committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
	return b
}

func MustString(obj any) string {
	b, _ := ToBytes(obj)

	return *(*string)(unsafe.Pointer(&b))
}

func MustStringSafe(obj any) string {
	b, _ := ToBytes(obj)

	return string(b)
}

func Pretty(i any) string {
	ss, _ := json.MarshalIndent(i, "", "  ")
Vladimir Barsukov's avatar
lint    
Vladimir Barsukov committed
56

Vladimir Barsukov's avatar
Vladimir Barsukov committed
57
58
	return string(ss)
}