github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/perf/json/utils.go (about)

     1  package json
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  )
     7  
     8  // Load reads JSON-encoded data from the named file at path and stores
     9  // the result in the value pointed to by v.
    10  func Load(path string, v any) error {
    11  	file, err := os.Open(path)
    12  	if err != nil {
    13  		return err
    14  	}
    15  	defer file.Close()
    16  	err = NewDecoder(file).Decode(v)
    17  	return err
    18  }
    19  
    20  // Dump writes v to the named file at path using JSON encoding.
    21  // It disables HTMLEscape.
    22  // Optionally indent can be applied to the output,
    23  // empty prefix and indent disables indentation.
    24  // The output is friendly to read by humans.
    25  func Dump(path string, v any, prefix, indent string) error {
    26  	file, err := os.Create(path)
    27  	if err != nil {
    28  		return err
    29  	}
    30  	defer file.Close()
    31  	return Fdump(file, v, prefix, indent)
    32  }
    33  
    34  // Fdump writes v to the given io.Writer using JSON encoding.
    35  // It disables HTMLEscape.
    36  // Optionally indent can be applied to the output,
    37  // empty prefix and indent disables indentation.
    38  // The output is friendly to read by humans.
    39  func Fdump(w io.Writer, v any, prefix, indent string) error {
    40  	return NewEncoder(w).
    41  		SetEscapeHTML(false).
    42  		SetIndent(prefix, indent).
    43  		Encode(v)
    44  }