如何用括号打印JSON?

时间:2021-07-23 01:49:32

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.

我可以使用下面的代码很好地缩进我的JSON,它打印出类似于第一个输出的东西。但我希望输出用数组括起来并正确缩进,就像在第二个输出中一样。

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

        ]
    }
]

1 个解决方案

#1


1  

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

只需将变量x包装在单个元素切片中。切片被编码为JSON数组(使用方括号):

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

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

#1


1  

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

只需将变量x包装在单个元素切片中。切片被编码为JSON数组(使用方括号):

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

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