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

NameTypeDescription
vanyGo value to encode or destination pointer to decode, depending on the operation.
prefixstringPrefix added to indented output lines.
indentstringIndentation 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)) }
Go Reference