sharedutils/osutils/json.go
2023-02-04 20:47:42 +03:00

48 lines
1.0 KiB
Go

package osutils
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
func WriteStructAsJSON(data interface{}, versionJsonPath string) error {
file, _ := json.MarshalIndent(data, "", " ")
directory, err := GetParentDir(versionJsonPath)
if err != nil {
return err
}
err = os.MkdirAll(directory+"/", os.ModePerm)
if err != nil {
return err
}
err = ioutil.WriteFile(versionJsonPath, 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)
}
// 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
}