Skip to content

File Operation Functions

The json package provides file operation functions, supporting file read/write and streaming I/O.

File Read Functions

LoadFromFile

Signature: func LoadFromFile(filePath string, cfg ...Config) (string, error)

Loads JSON data from a file.

Parameters

NameTypeRequiredDescription
filePathstringYesFile path
cfgConfigNoOptional configuration
go
data, err := json.LoadFromFile("config.json")
if err != nil {
    panic(err)
}
fmt.Println(data)

SaveToFile

Signature: func SaveToFile(filePath string, data any, cfg ...Config) error

Saves JSON data to a file.

Parameters

NameTypeRequiredDescription
filePathstringYesFile path
dataanyYesData to save
cfgConfigNoOptional configuration
go
err := json.SaveToFile("output.json", map[string]any{
    "name": "Alice",
    "age":  30,
})
if err != nil {
    panic(err)
}

MarshalToFile

Signature: func MarshalToFile(filePath string, data any, cfg ...Config) error

Serializes data and writes it to a file.

Parameters

NameTypeRequiredDescription
filePathstringYesFile path
dataanyYesData to serialize
cfgConfigNoOptional configuration
go
err := json.MarshalToFile("data.json", myStruct)

UnmarshalFromFile

Signature: func UnmarshalFromFile(filePath string, v any, cfg ...Config) error

Reads and deserializes data from a file.

Parameters

NameTypeRequiredDescription
filePathstringYesFile path
vanyYesTarget object pointer
cfgConfigNoOptional configuration
go
var config MyConfig
err := json.UnmarshalFromFile("config.json", &config)
if err != nil {
    panic(err)
}

LoadFromReader

Signature: func LoadFromReader(reader io.Reader, cfg ...Config) (string, error)

Loads JSON data from an io.Reader. Suitable for reading JSON from streaming sources like network connections, HTTP request bodies, etc.

Parameters

NameTypeRequiredDescription
readerio.ReaderYesData source
cfgConfigNoOptional configuration
go
// Read from HTTP response body
resp, _ := http.Get("https://api.example.com/data")
defer resp.Body.Close()
data, err := json.LoadFromReader(resp.Body)

// Read from a string
data, err = json.LoadFromReader(strings.NewReader(`{"name":"test"}`))

SaveToWriter

Signature: func SaveToWriter(writer io.Writer, data any, cfg ...Config) error

Writes JSON data to an io.Writer.

Parameters

NameTypeRequiredDescription
writerio.WriterYesOutput target
dataanyYesData to write
cfgConfigNoOptional configuration
go
var buf bytes.Buffer
err := json.SaveToWriter(&buf, map[string]any{"name": "test"})
if err != nil {
    panic(err)
}

See Also