github.com/swisscom/cloudfoundry-cli@v7.1.0+incompatible/cf/util/json/json_parser.go (about) 1 package json 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io/ioutil" 7 "os" 8 ) 9 10 func ParseJSONArray(path string) ([]map[string]interface{}, error) { 11 if path == "" { 12 return nil, nil 13 } 14 15 bytes, err := readJSONFile(path) 16 if err != nil { 17 return nil, err 18 } 19 20 stringMaps := []map[string]interface{}{} 21 err = json.Unmarshal(bytes, &stringMaps) 22 if err != nil { 23 return nil, fmt.Errorf("Incorrect json format: %s", err.Error()) 24 } 25 26 return stringMaps, nil 27 } 28 29 func ParseJSONFromFileOrString(fileOrJSON string) (map[string]interface{}, error) { 30 var jsonMap map[string]interface{} 31 var err error 32 var bytes []byte 33 34 if fileOrJSON == "" { 35 return nil, nil 36 } 37 38 if fileExists(fileOrJSON) { 39 bytes, err = readJSONFile(fileOrJSON) 40 if err != nil { 41 return nil, err 42 } 43 } else { 44 bytes = []byte(fileOrJSON) 45 } 46 47 jsonMap, err = parseJSON(bytes) 48 49 if err != nil { 50 return nil, err 51 } 52 53 return jsonMap, nil 54 } 55 56 func fileExists(path string) bool { 57 _, err := os.Stat(path) 58 return err == nil 59 } 60 61 func readJSONFile(path string) ([]byte, error) { 62 file, err := os.Open(path) 63 if err != nil { 64 return nil, err 65 } 66 67 bytes, err := ioutil.ReadAll(file) 68 if err != nil { 69 return nil, err 70 } 71 72 return bytes, nil 73 } 74 75 func parseJSON(bytes []byte) (map[string]interface{}, error) { 76 stringMap := map[string]interface{}{} 77 err := json.Unmarshal(bytes, &stringMap) 78 if err != nil { 79 return nil, fmt.Errorf("Incorrect json format: %s", err.Error()) 80 } 81 82 return stringMap, nil 83 }