49 lines
1.0 KiB
Go
49 lines
1.0 KiB
Go
package osutils
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"os"
|
|
)
|
|
|
|
func WriteStructAsJSON(data interface{}, JsonPath string) error {
|
|
file, _ := json.MarshalIndent(data, "", " ")
|
|
|
|
directory, err := GetParentDir(JsonPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = os.MkdirAll(directory+"/", os.ModePerm)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = ioutil.WriteFile(JsonPath, file, 0644)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func ReadJsonFromDisk(target interface{}, filePath string) error {
|
|
// Open our jsonFile
|
|
jsonFile, err := os.Open(filePath)
|
|
// if we os.Open returns an error then handle it
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return err
|
|
}
|
|
|
|
// fmt.Println("Successfully Opened users.json")
|
|
// defer the closing of our jsonFile so that we can parse it later on
|
|
defer jsonFile.Close()
|
|
|
|
// read our opened xmlFile as a byte array.
|
|
byteValue, _ := ioutil.ReadAll(jsonFile)
|
|
|
|
// we unmarshal our byteArray which contains our
|
|
// jsonFile's content into 'users' which we defined above
|
|
json.Unmarshal(byteValue, &target)
|
|
return nil
|
|
}
|