isle/go/jsonutil/jsonutil.go

59 lines
1.4 KiB
Go
Raw Permalink Normal View History

// Package contains utility functions and types related to (un)marshaling JSON.
package jsonutil
import (
"encoding/json"
"fmt"
"io"
"os"
)
// LoadFile reads the file at the given path and unmarshals it into the
// given pointer.
func LoadFile(into any, path string) error {
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("opening file: %w", err)
}
defer file.Close()
if err = json.NewDecoder(file).Decode(into); err != nil {
return fmt.Errorf("decoding json: %w", err)
}
return nil
}
// WriteFile encodes the given data as a JSON document, and writes it to the
// given file path, overwriting any previous data.
func WriteFile(data any, path string, fileMode os.FileMode) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fileMode)
if err != nil {
return fmt.Errorf("opening file: %w", err)
}
defer file.Close()
if err = json.NewEncoder(file).Encode(data); err != nil {
return fmt.Errorf("writing/encoding file: %w", err)
}
return nil
}
// WriteIndented is a helper which calls json.MarshalIndent on the given
// value and writes the result to the given io.Writer.
func WriteIndented(into io.Writer, v any) error {
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
return fmt.Errorf("json marshaling: %w", err)
}
if _, err := os.Stdout.Write(b); err != nil {
return fmt.Errorf("writing: %w", err)
}
return nil
}