Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format JSON with indentation in Go [duplicate]

Tags:

json

go

After I do

    json, err := json.Marshal(buf)

I get something like:

{"a":123,"b":"abc"}

But what I want is an indented version of this:

{
    "a": 123,
    "b": "abc"
}

How?

like image 598
exebook Avatar asked Aug 27 '17 07:08

exebook


People also ask

How do I indent JSON in Golang?

The easiest way to do this is with MarshalIndent , which will let you specify how you would like it indented via the indent argument. Thus, json. MarshalIndent(data, "", " ") will pretty-print using four spaces for indentation.

How do I indent in JSON?

JSON conventions¶ Format JSON files to be human readable. Use four spaces for indentation (matching OpenStack conventions used in Python and shell scripts). Do not use tab characters in the code, always use spaces. Use one space after the name-separator (colon).

Do indentations matter in JSON?

JSON is a serialization format, not a presentation format. As such, there is no "standard" indentation - JSON is typically sent as compactly as possible.


1 Answers

Use json.MarshalIndent(group, "", "\t"), try this:

package main

import (
    "encoding/json"
    "fmt"
    "os"
)

func main() {
    type ColorGroup struct {
        ID     int
        Name   string
        Colors []string
    }
    group := ColorGroup{
        ID:     1,
        Name:   "Reds",
        Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
    }
    b, err := json.MarshalIndent(group, "", "\t")
    if err != nil {
        fmt.Println("error:", err)
    }
    os.Stdout.Write(b)
}

output:

{
    "ID": 1,
    "Name": "Reds",
    "Colors": [
        "Crimson",
        "Red",
        "Ruby",
        "Maroon"
    ]
}
like image 156
wasmup Avatar answered Oct 21 '22 00:10

wasmup