ab11 ab11 - 4 months ago 20
JSON Question

How to pretty print JSON with brackets?

I am able to nicely indent my JSON with the below code, it prints something like first output. But I would like the output to be enclosed with an array and to be properly indented, like in the second output.

j, err := json.MarshalIndent(x, "", " ")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(j))
}

{
"A" : "x",
"B" : "y",
"C" : [
{
"A" ...
}
]
}


Like so.

[
{
"A" : "x",
"B" : "y",
"C" : [
{
"A" ...
}

]
}
]

Answer

Just wrap your variable x in a single element slice. The slice gets encoded to a JSON array (which use the square brackets):

j, err := json.MarshalIndent([]interface{}{x}, "", "  ")

https://play.golang.org/p/Q9kqTdwoO6

Comments