Standard library / encoding/json
encoding/json.MarshalIndent()
Encode a Go value as formatted JSON with a line prefix and indentation. It uses the same value rules as Marshal. Expected stdout: '[\n 1,\n 2\n]\n'.
Formal Syntax & Structure
go syntaxgo
func MarshalIndent(v any, prefix, indent string) ([]byte, error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| v | any | Go value to encode or destination pointer to decode, depending on the operation. |
| prefix | string | Prefix added to indented output lines. |
| indent | string | Indentation string for each nesting level. |
Return Value
([]byte, error)
Encoded bytes and an error (nil on success).
Working Example
Example Snippetgo
package main
import ( "encoding/json" "fmt")
func must(e error) { if e != nil { panic(e) }}
func main() { b, e := json.MarshalIndent([]int{1, 2}, "", " "); must(e); fmt.Println(string(b)) }