How to Write JSON File in Go: Simple Guide with Example
To write a JSON file in Go, use the
encoding/json package to convert data into JSON format and the os package to create and write to a file. Use json.MarshalIndent for readable JSON and os.WriteFile or os.Create with file.Write to save the JSON data to a file.Syntax
Here is the basic syntax to write JSON data to a file in Go:
json.MarshalIndent(data, "", " "): Converts Go data to formatted JSON bytes.os.WriteFile(filename, jsonBytes, 0644): Writes JSON bytes to a file with permissions.
go
jsonBytes, err := json.MarshalIndent(data, "", " ") if err != nil { // handle error } err = os.WriteFile("file.json", jsonBytes, 0644) if err != nil { // handle error }
Example
This example shows how to create a struct, convert it to JSON, and write it to a file named data.json. It uses json.MarshalIndent for pretty JSON formatting and os.WriteFile to save the file.
go
package main import ( "encoding/json" "fmt" "os" ) type Person struct { Name string `json:"name"` Age int `json:"age"` } func main() { person := Person{Name: "Alice", Age: 30} jsonBytes, err := json.MarshalIndent(person, "", " ") if err != nil { fmt.Println("Error encoding JSON:", err) return } err = os.WriteFile("data.json", jsonBytes, 0644) if err != nil { fmt.Println("Error writing file:", err) return } fmt.Println("JSON file written successfully") }
Output
JSON file written successfully
Common Pitfalls
Common mistakes when writing JSON files in Go include:
- Not checking errors from
json.MarshalIndentor file operations, which can cause silent failures. - Using
json.Marshalwithout indentation, making JSON hard to read. - Forgetting to set proper file permissions, which can cause permission errors.
- Trying to write to a file without creating or opening it properly.
go
package main import ( "encoding/json" "fmt" "os" ) func main() { data := map[string]string{"hello": "world"} // Wrong: ignoring error from Marshal jsonBytes, _ := json.Marshal(data) // Wrong: writing to file without checking error _ = os.WriteFile("output.json", jsonBytes, 0000) // wrong permissions // Right way: jsonBytes, err := json.MarshalIndent(data, "", " ") if err != nil { fmt.Println("Error encoding JSON:", err) return } err = os.WriteFile("output.json", jsonBytes, 0644) if err != nil { fmt.Println("Error writing file:", err) return } fmt.Println("File written correctly") }
Output
File written correctly
Quick Reference
Remember these key points when writing JSON files in Go:
- Use
json.MarshalIndentfor readable JSON output. - Use
os.WriteFileto write bytes to a file simply. - Always check errors from JSON encoding and file writing.
- Set file permissions to
0644for normal read/write access.
Key Takeaways
Use encoding/json's MarshalIndent to convert Go data to pretty JSON bytes.
Write JSON bytes to a file with os.WriteFile and proper permissions (0644).
Always check errors when encoding JSON and writing files to avoid silent failures.
Set file permissions correctly to ensure the file is accessible.
Avoid ignoring errors and use indentation for better JSON readability.