Reputation: 20100
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" ...
}
]
}
]
Upvotes: 1
Views: 2088
Reputation:
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
Upvotes: 1