【问题标题】:Format JSON with indentation in Go [duplicate]在 Go 中使用缩进格式化 JSON [重复]
【发布时间】:2017-08-27 07:57:00
【问题描述】:

之后

    json, err := json.Marshal(buf)

我得到类似的东西:

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

但我想要的是这个的缩进版本:

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

怎么做?

【问题讨论】:

  • 你想在 chrome 浏览器中看到它的格式,然后使用 JSON Formatter 扩展。
  • 使用MarshalIndent
  • @Rakib 不,只是想打印到控制台或保存到文件

标签: json go


【解决方案1】:

使用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"
    ]
}

【讨论】:

  • 有没有办法让基本类型的列表不换行?
  • @NikolaiEhrhardt:您可以自己编写自定义 JSON 编组。
  • 是的,会变成很多工作 =)。我也认为它应该是可能的,有反射和任何东西。
  • @NikolaiEhrhardt: 正则表达式: (\[[^[\]]+\]) 试试this
  • 我只想格式化基本类型的列表...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-03
  • 2023-01-03
  • 2022-08-10
  • 2014-12-12
  • 2021-06-29
相关资源
最近更新 更多