在Go中使用缩进格式化JSON

时间:2017-08-27 07:57:00

标签: json go

我做完

a = A.back();
A.pop_back();

我得到类似的东西:

    json, err := json.Marshal(buf)

但我想要的是缩进版本:

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

如何?

1 个答案:

答案 0 :(得分:3)

使用json.MarshalIndent(group, "", "\t"),尝试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)
}

输出:

{
    "ID": 1,
    "Name": "Reds",
    "Colors": [
        "Crimson",
        "Red",
        "Ruby",
        "Maroon"
    ]
}