2023-02-04 17:47:42 +00:00
|
|
|
package osutils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2023-02-14 22:15:59 +00:00
|
|
|
func WriteStructAsJSON(data interface{}, JsonPath string) error {
|
2023-02-04 17:47:42 +00:00
|
|
|
file, _ := json.MarshalIndent(data, "", " ")
|
|
|
|
|
2023-02-14 22:15:59 +00:00
|
|
|
directory, err := GetParentDir(JsonPath)
|
2023-02-04 17:47:42 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = os.MkdirAll(directory+"/", os.ModePerm)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-02-14 22:15:59 +00:00
|
|
|
err = ioutil.WriteFile(JsonPath, file, 0644)
|
2023-02-04 17:47:42 +00:00
|
|
|
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)
|
2023-02-14 22:15:59 +00:00
|
|
|
return err
|
2023-02-04 17:47:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|