ab11
ab11

Reputation: 20100

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

        ]
    }
]

Upvotes: 1

Views: 2088

Answers (1)

user142162
user142162

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

Related Questions