Golangで`json.MarshalIndent`を使用する方法
Emily Parker
Product Engineer · Leapcell

Key Takeaways
json.MarshalIndent
は、カスタマイズ可能なインデントとプレフィックスでJSONをフォーマットします。- JSONの可読性を向上させ、デバッグやログ記録に役立ちます。
- サポートされていないデータ型による問題を避けるためには、適切なエラー処理が必要です。
Introduction
GolangでJSONを扱う際、encoding/json
パッケージは、Goのデータ構造をJSON形式にシリアライズするためのjson.Marshal
関数を提供します。しかし、json.Marshal
のデフォルトの出力はコンパクトであり、余分な空白やインデントは含まれていません。人間が読める、フォーマットされたJSON出力が必要な場合は、json.MarshalIndent
を使用できます。
この記事では、json.MarshalIndent
を効果的に使用する方法を説明し、実践的な例を提供します。
Understanding json.MarshalIndent
json.MarshalIndent
関数はjson.Marshal
と似ていますが、インデント設定を指定できます。その関数シグネチャは次のとおりです。
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
v
はJSONにシリアライズされるGoの値です。prefix
は、出力の各行にプレフィックスとして付加される文字列です。indent
は、フォーマットに使用されるインデント文字を定義します。- この関数は、フォーマットされたJSONを含む
[]byte
と、シリアライズが失敗した場合のerror
を返します。
Basic Example
json.MarshalIndent
を使用した簡単な例を見てみましょう。
package main import ( "encoding/json" "fmt" ) type User struct { Name string `json:"name"` Age int `json:"age"` Email string `json:"email"` } func main() { user := User{ Name: "Alice", Age: 25, Email: "alice@example.com", } // MarshalIndent with two spaces for indentation jsonData, err := json.MarshalIndent(user, "", " ") if err != nil { fmt.Println("Error:", err) return } // Convert JSON bytes to string and print fmt.Println(string(jsonData)) }
Output
{ "name": "Alice", "age": 25, "email": "alice@example.com" }
Explanation
- 2番目の引数(
""
)は空のプレフィックスです。つまり、各行の先頭に追加の文字は付きません。 - 3番目の引数(
" "
)は、各インデントレベルが2つのスペースを使用することを指定します。 - 出力JSONは、改行とインデントで適切にフォーマットされており、読みやすくなっています。
Customizing Indentation
indent
パラメータをカスタマイズして、さまざまな書式スタイルを使用できます。
Using Tabs Instead of Spaces
jsonData, err := json.MarshalIndent(user, "", "\t")
これにより、スペースの代わりにタブインデントを使用したJSONが生成されます。
Adding a Prefix
jsonData, err := json.MarshalIndent(user, "> ", " ")
これにより、各行の前に"> "
プレフィックスが追加されます。
> { > "name": "Alice", > "age": 25, > "email": "alice@example.com" > }
Handling Nested Structures
json.MarshalIndent
は、ネストされた構造体でもうまく機能します。以下は、埋め込み構造体を使用した例です。
type Address struct { City string `json:"city"` State string `json:"state"` } type UserWithAddress struct { Name string `json:"name"` Age int `json:"age"` Email string `json:"email"` Address Address `json:"address"` } func main() { user := UserWithAddress{ Name: "Bob", Age: 30, Email: "bob@example.com", Address: Address{ City: "New York", State: "NY", }, } jsonData, err := json.MarshalIndent(user, "", " ") if err != nil { fmt.Println("Error:", err) return } fmt.Println(string(jsonData)) }
Output
{ "name": "Bob", "age": 30, "email": "bob@example.com", "address": { "city": "New York", "state": "NY" } }
Error Handling
json.MarshalIndent
がサポートされていない型(チャネルや関数など)を検出すると、エラーが返されます。返されたJSONデータを使用する前に、必ずエラーを確認してください。
jsonData, err := json.MarshalIndent(user, "", " ") if err != nil { fmt.Println("Error:", err) return } fmt.Println(string(jsonData))
Conclusion
json.MarshalIndent
は、インデントを使用して人間が読めるJSONを生成するためのGolangの便利な関数です。プレフィックスとインデント文字列を指定することにより、ニーズに合わせて出力形式をカスタマイズできます。これは、JSONレスポンスのログ記録、デバッグ、または構成ファイルを読みやすい形式で保存する場合に特に役立ちます。
json.MarshalIndent
を習得することで、JSONデータの可読性を向上させ、開発およびデバッグのシナリオで扱いやすくすることができます。
FAQs
json.Marshal
はコンパクトなJSONを生成し、json.MarshalIndent
は可読性を高めるためにインデントを使用してJSONをフォーマットします。
はい、json.MarshalIndent
のインデントパラメータとして"\t"
を渡すことで可能です。
json.MarshalIndent
はエラーを返すため、常に適切にエラーを処理する必要があります。
We are Leapcell, your top choice for hosting Go projects.
Leapcell is the Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis:
Multi-Language Support
- Develop with Node.js, Python, Go, or Rust.
Deploy unlimited projects for free
- pay only for usage — no requests, no charges.
Unbeatable Cost Efficiency
- Pay-as-you-go with no idle charges.
- Example: $25 supports 6.94M requests at a 60ms average response time.
Streamlined Developer Experience
- Intuitive UI for effortless setup.
- Fully automated CI/CD pipelines and GitOps integration.
- Real-time metrics and logging for actionable insights.
Effortless Scalability and High Performance
- Auto-scaling to handle high concurrency with ease.
- Zero operational overhead — just focus on building.
Explore more in the Documentation!
Follow us on X: @LeapcellHQ