github.com/codingeasygo/util@v0.0.0-20231206062002-1ce2f004b7d9/xmap/file.go (about) 1 package xmap 2 3 import ( 4 "encoding/json" 5 "io/ioutil" 6 "os" 7 "path/filepath" 8 ) 9 10 // ReadJSON will read json data from file and parset to M 11 func ReadJSON(filename string) (data M, err error) { 12 jsonData, err := ioutil.ReadFile(filename) 13 if err == nil { 14 err = json.Unmarshal(jsonData, &data) 15 } 16 return 17 } 18 19 // WriteJSON will marshal M to json and write to file 20 func WriteJSON(data M, filename string) (err error) { 21 dir, _ := filepath.Split(filename) 22 os.MkdirAll(dir, os.ModePerm) 23 jsonData, err := json.MarshalIndent(data, "", " ") 24 if err == nil { 25 ioutil.WriteFile(filename, jsonData, os.ModePerm) 26 } 27 return 28 }