英文:
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"
]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论