go结构体打印格式化成json

需要用到json.MarshalIndent 方法

官方的注释是:

MarshalIndent类似于Marshal,但应用Indent来格式化输出。

输出中的每个JSON元素都将以一个新行开始,该新行以 前缀 开头,后跟一个或多个根据缩进嵌套的缩进副本。

就是会在每个字段以及值之后加回车换行

也可以自己给新行加前缀后缀

用来打印成方便查看的格式,非常适合

package main

import (
	"encoding/json"
	"fmt"
)

type ToolStruct struct {
	A int64
	B string
	C string
}

func main() {
	i := &ToolStruct{}
	i.A = 128
	i.B = "asdf"
	i.C = "qwer"
	res, _ := json.MarshalIndent(i, "", "   ")
	fmt.Println(i)
	fmt.Println(string(res))
}

/*
打印结果
&{128 asdf qwer}
{
   "A": 128,
   "B": "asdf",
   "C": "qwer"
}
*/

显然,下面这种的可读性更高

posted @ 2023-02-26 20:12  厚礼蝎  阅读(465)  评论(0编辑  收藏  举报