-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
79 lines (68 loc) · 1.88 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package jsonhelper
import (
"bytes"
j "encoding/json"
"fmt"
"io"
"os"
)
// WriteToJSONFile writes the specified object as a JSON file to the specified path
func WriteToJSONFile(path string, object interface{}, isOverwrite bool) error {
if path == "" {
return fmt.Errorf("path is not specified")
}
if object == nil {
return fmt.Errorf("object cannot be empty")
}
if _, err := os.Stat(path); os.IsExist(err) {
if !isOverwrite {
return fmt.Errorf("file [%s] is already exist", path)
}
errRemove := os.Remove(path)
if errRemove != nil {
return errRemove
}
}
file, errOpen := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if errOpen != nil {
return errOpen
}
defer file.Close()
return j.NewEncoder(file).Encode(object)
}
// GetJSONString returns a JSON string of the specified object
func GetJSONString(object interface{}) (string, error) {
buf, err := GetJSONStringBuffer(object)
return buf.String(), err
}
// GetJSONStringBuffer returns a buffer of JSON string of the specified object
func GetJSONStringBuffer(object interface{}) (*bytes.Buffer, error) {
buf := bytes.NewBufferString("")
encoder := j.NewEncoder(buf)
err := encoder.Encode(object)
if err != nil {
return nil, err
}
return buf, nil
}
// ParseJSONReader parses JSON string from the specified reader and fill the content
// into the output object
func ParseJSONReader(json io.Reader, output interface{}) error {
err := j.NewDecoder(json).Decode(&output)
if err != nil {
return err
}
return nil
}
// ParseJSONString parses JSON string from the specified reader and fill the content
// into the output object
func ParseJSONString(jsonString string, output interface{}) error {
buf := bytes.NewBufferString(jsonString)
return ParseJSONReader(buf, output)
}
func ParseJSONFromBytes(v interface{}, b []byte) (err error) {
if err = j.Unmarshal(b, v); err != nil {
return err
}
return nil
}