Format JSON with indentation in Go

huangapple go评论90阅读模式
英文:

Format JSON with indentation in Go

问题

在执行json, err := json.Marshal(buf)之后,你得到了以下结果:

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

但是你想要的是一个带缩进的版本,如下所示:

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

你想知道如何实现这个效果。

英文:

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?

答案1

得分: 24

使用json.MarshalIndent(group, "", "\t"),尝试这个

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"
	]
}
英文:

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

huangapple
  • 本文由 发表于 2017年8月27日 15:57:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/45902847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定