forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_parser.go
83 lines (66 loc) · 1.42 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
package json
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
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, fmt.Errorf("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, fmt.Errorf("Incorrect json format: %s", err.Error())
}
return stringMap, nil
}