有人知道在Go中漂亮打印JSON输出的简单方法吗?

我想漂亮地打印json的结果。Marshal,以及格式化现有的JSON字符串,以便更容易阅读。


当前回答

package cube

import (
    "encoding/json"
    "fmt"
    "github.com/magiconair/properties/assert"
    "k8s.io/api/rbac/v1beta1"
    v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "testing"
)

func TestRole(t *testing.T)  {
    clusterRoleBind := &v1beta1.ClusterRoleBinding{
        ObjectMeta: v1.ObjectMeta{
            Name: "serviceaccounts-cluster-admin",
        },
        RoleRef: v1beta1.RoleRef{
            APIGroup: "rbac.authorization.k8s.io",
            Kind:     "ClusterRole",
            Name:     "cluster-admin",
        },
        Subjects: []v1beta1.Subject{{
            Kind:     "Group",
            APIGroup: "rbac.authorization.k8s.io",
            Name:     "system:serviceaccounts",
        },
        },
    }
    b, err := json.MarshalIndent(clusterRoleBind, "", "  ")
    assert.Equal(t, nil, err)
    fmt.Println(string(b))
}

其他回答

我很沮丧,因为在Go中缺少一种快速、高质量的方法来将JSON编组为彩色字符串,所以我写了自己的编组程序ColorJSON。

有了它,你可以用很少的代码轻松生成如下输出:

package main

import (
    "fmt"
    "encoding/json"

    "github.com/TylerBrock/colorjson"
)

func main() {
    str := `{
      "str": "foo",
      "num": 100,
      "bool": false,
      "null": null,
      "array": ["foo", "bar", "baz"],
      "obj": { "a": 1, "b": 2 }
    }`

    var obj map[string]interface{}
    json.Unmarshal([]byte(str), &obj)

    // Make a custom formatter with indent set
    f := colorjson.NewFormatter()
    f.Indent = 4

    // Marshall the Colorized JSON
    s, _ := f.Marshal(obj)
    fmt.Println(string(s))
}

我现在正在为它写文档,但我很高兴能分享我的解决方案。

一个简单的货架上漂亮的打印机。可以通过以下方法将其编译为二进制文件:

go build -o jsonformat jsonformat.go

它从标准输入读取,写入标准输出,并允许设置缩进:

package main

import (
    "bytes"
    "encoding/json"
    "flag"
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    indent := flag.String("indent", "  ", "indentation string/character for formatter")
    flag.Parse()
    src, err := ioutil.ReadAll(os.Stdin)
    if err != nil {
        fmt.Fprintf(os.Stderr, "problem reading: %s", err)
        os.Exit(1)
    }

    dst := &bytes.Buffer{}
    if err := json.Indent(dst, src, "", *indent); err != nil {
        fmt.Fprintf(os.Stderr, "problem formatting: %s", err)
        os.Exit(1)
    }
    if _, err = dst.WriteTo(os.Stdout); err != nil {
        fmt.Fprintf(os.Stderr, "problem writing: %s", err)
        os.Exit(1)
    }
}

它允许运行bash命令,如:

cat myfile | jsonformat | grep "key"

使用json。带字符串的MarshalIndent

这个easyPrint函数接受参数数据(任何类型的数据),并将其打印成预期的(漂亮的)JSON格式。

import (
  "encoding/json"
  "log"
)

func easyPrint(data interface{}) {
  manifestJson, _ := json.MarshalIndent(data, "", "  ")

  log.Println(string(manifestJson))
}

使用name参数。

TODO:使参数名可选。

func easyPrint(data interface{}, name string) {
  manifestJson, _ := json.MarshalIndent(data, "", "  ")

  log.Println(name + " ->", string(manifestJson))
}

如果您想将一个对象转换为JSON,那么接受的答案是非常好的。这个问题还提到了漂亮打印任何JSON字符串,这就是我试图做的。我只是想从POST请求(特别是CSP违反报告)漂亮地记录一些JSON。

要使用MarshalIndent,必须将其解编组到一个对象中。如果你需要,那就去吧,但我不需要。如果你只是需要漂亮地打印一个字节数组,普通缩进是你的朋友。

这是我最后得出的结论:

import (
    "bytes"
    "encoding/json"
    "log"
    "net/http"
)

func HandleCSPViolationRequest(w http.ResponseWriter, req *http.Request) {
    body := App.MustReadBody(req, w)
    if body == nil {
        return
    }

    var prettyJSON bytes.Buffer
    error := json.Indent(&prettyJSON, body, "", "\t")
    if error != nil {
        log.Println("JSON parse error: ", error)
        App.BadRequest(w)
        return
    }

    log.Println("CSP Violation:", string(prettyJSON.Bytes()))
}

MarshalIndent将允许您输出带有缩进和间距的JSON。例如:

{
    "data": 1234
}

缩进参数指定要缩进的字符序列。因此,json。MarshalIndent(data, "", "")将使用四个空格进行缩进。