package json_io import ( "encoding/json" "fmt" "os" "git.tswf.io/incredible-go/incredible-go-core/pkg/io/files" ) func ReadFromJsonBytes[T any](jsonBytes []byte) (*T, error) { var result T err := json.Unmarshal(jsonBytes, &result) if err != nil { return nil, err } return &result, nil } func WriteToJsonBytes[T any](value *T) ([]byte, error) { content, err := json.Marshal(value) if err != nil { return nil, err } return content, nil } func ReadFromJsonString[T any](jsonString string) (*T, error) { return ReadFromJsonBytes[T]([]byte(jsonString)) } func WriteToJsonString[T any](value *T) (string, error) { jsonBytes, err := WriteToJsonBytes(value) if err != nil { return "", err } return string(jsonBytes), nil } func ReadFromJsonFile[T any](jsonFileLocation string) (*T, error) { fileInfo, err := os.Stat(jsonFileLocation) if err != nil { return nil, err } if fileInfo.IsDir() { return nil, fmt.Errorf("json file '%s' can not be a directory", jsonFileLocation) } jsonFileContentBytes, err := os.ReadFile(jsonFileLocation) if err != nil { return nil, err } return ReadFromJsonBytes[T](jsonFileContentBytes) } func WriteToJsonFile[T any](jsonFileLocation string, value *T) ([]byte, error) { jsonBytes, err := WriteToJsonBytes(value) if err != nil { return nil, err } file, err := files.OpenFileForWriting(jsonFileLocation) if err != nil { return nil, err } _, err = file.Write(jsonBytes) if err != nil { return nil, err } return jsonBytes, nil }