forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_parser.go
84 lines (66 loc) · 1.46 KB
/
json_parser.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
79
80
81
82
83
84
package json
import (
"encoding/json"
"io/ioutil"
"os"
"github.com/cloudfoundry/cli/cf/errors"
)
func ParseJsonArray(path string) ([]map[string]interface{}, error) {
if path == "" {
return nil, nil
}
bytes, err := readJsonFile(path)
if err != nil {
return nil, err
}
stringMaps := []map[string]interface{}{}
err = json.Unmarshal(bytes, &stringMaps)
if err != nil {
return nil, errors.NewWithFmt("Incorrect json format: %s", err.Error())
}
return stringMaps, nil
}
func ParseJsonFromFileOrString(fileOrJson string) (map[string]interface{}, error) {
var jsonMap map[string]interface{}
var err error
var bytes []byte
if fileOrJson == "" {
return nil, nil
}
if fileExists(fileOrJson) {
bytes, err = readJsonFile(fileOrJson)
if err != nil {
return nil, err
}
} else {
bytes = []byte(fileOrJson)
}
jsonMap, err = parseJson(bytes)
if err != nil {
return nil, err
}
return jsonMap, nil
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func readJsonFile(path string) ([]byte, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
bytes, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
return bytes, nil
}
func parseJson(bytes []byte) (map[string]interface{}, error) {
stringMap := map[string]interface{}{}
err := json.Unmarshal(bytes, &stringMap)
if err != nil {
return nil, errors.NewWithFmt("Incorrect json format: %s", err.Error())
}
return stringMap, nil
}