简体   繁体   English

如何使用 Go 漂亮地打印 JSON?

[英]How can I pretty-print JSON using Go?

Does anyone know of a simple way to pretty-print JSON output in Go?有谁知道在 Go 中漂亮打印 JSON output 的简单方法?

The stock http://golang.org/pkg/encoding/json/ package does not seem to include functionality for this (EDIT: it does, see accepted answer) and a quick google doesn't turn up anything obvious. 库存 http://golang.org/pkg/encoding/json/ package 似乎不包括此功能 (编辑:确实如此,请参阅已接受的答案)并且快速谷歌并没有发现任何明显的东西。

Uses I'm looking for are both pretty-printing the result of json.Marshal and just formatting a string full of JSON from wherever, so it's easier to read for debug purposes.我正在寻找的用途既可以漂亮地打印json.Marshal的结果,也可以从任何地方格式化一个充满 JSON 的字符串,因此更容易阅读以进行调试。

By pretty-print, I assume you mean indented, like so通过漂亮的印刷,我假设你的意思是缩进,就像这样

{
    "data": 1234
}

rather than而不是

{"data":1234}

The easiest way to do this is with MarshalIndent , which will let you specify how you would like it indented via the indent argument.最简单的方法是使用MarshalIndent ,它可以让你通过indent参数指定你希望它如何indent Thus, json.MarshalIndent(data, "", " ") will pretty-print using four spaces for indentation.因此, json.MarshalIndent(data, "", " ")将使用四个空格进行漂亮打印。

The accepted answer is great if you have an object you want to turn into JSON.如果您有一个要转换为 JSON 的对象,那么接受的答案就很好。 The question also mentions pretty-printing just any JSON string, and that's what I was trying to do.这个问题还提到了漂亮地打印任何 JSON 字符串,这就是我想要做的。 I just wanted to pretty-log some JSON from a POST request (specifically a CSP violation report ).我只是想从 POST 请求(特别是CSP 违规报告)中漂亮地记录一些 JSON。

To use MarshalIndent , you would have to Unmarshal that into an object.要使用MarshalIndent ,您必须将其Unmarshal为对象。 If you need that, go for it, but I didn't.如果你需要那个,去吧,但我没有。 If you just need to pretty-print a byte array, plain Indent is your friend.如果你只需要漂亮地打印一个字节数组,普通的Indent就是你的朋友。

Here's what I ended up with:这是我的结果:

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()))
}

For better memory usage, I guess this is better:为了更好地使用内存,我想这更好:

var out io.Writer
enc := json.NewEncoder(out)
enc.SetIndent("", "    ")
if err := enc.Encode(data); err != nil {
    panic(err)
}

I was frustrated by the lack of a fast, high quality way to marshal JSON to a colorized string in Go so I wrote my own Marshaller called ColorJSON .我对在 Go 中缺乏快速、高质量的方式将 JSON 编组为彩色字符串感到沮丧,所以我编写了自己的 Marshaller 称为ColorJSON

With it, you can easily produce output like this using very little code:有了它,您可以使用很少的代码轻松生成这样的输出:

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))
}

I'm writing the documentation for it now but I was excited to share my solution.我现在正在为它编写文档,但我很高兴能分享我的解决方案。

Edit Looking back, this is non-idiomatic Go.编辑回过头来看,这是非惯用的 Go。 Small helper functions like this add an extra step of complexity.像这样的小辅助函数增加了额外的复杂性。 In general, the Go philosophy prefers to include the 3 simple lines over 1 tricky line.一般来说,围棋哲学更喜欢包含 3 条简单的代码而不是 1 条复杂的代码。


As @robyoder mentioned, json.Indent is the way to go.正如@robyoder 提到的, json.Indent是要走的路。 Thought I'd add this small prettyprint function:以为我会添加这个小的prettyprint功能:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

//dont do this, see above edit
func prettyprint(b []byte) ([]byte, error) {
    var out bytes.Buffer
    err := json.Indent(&out, b, "", "  ")
    return out.Bytes(), err
}

func main() {
    b := []byte(`{"hello": "123"}`)
    b, _ = prettyprint(b)
    fmt.Printf("%s", b)
}

https://go-sandbox.com/#/R4LWpkkHIN or http://play.golang.org/p/R4LWpkkHIN https://go-sandbox.com/#/R4LWpkkHINhttp://play.golang.org/p/R4LWpkkHIN

Here's what I use.这是我使用的。 If it fails to pretty print the JSON it just returns the original string.如果它无法漂亮地打印 JSON,它只会返回原始字符串。 Useful for printing HTTP responses that should contain JSON.用于打印包含 JSON 的 HTTP 响应。

import (
    "encoding/json"
    "bytes"
)

func jsonPrettyPrint(in string) string {
    var out bytes.Buffer
    err := json.Indent(&out, []byte(in), "", "\t")
    if err != nil {
        return in
    }
    return out.String()
}

Here is my solution :这是我的解决方案

import (
    "bytes"
    "encoding/json"
)

const (
    empty = ""
    tab   = "\t"
)

func PrettyJson(data interface{}) (string, error) {
    buffer := new(bytes.Buffer)
    encoder := json.NewEncoder(buffer)
    encoder.SetIndent(empty, tab)

    err := encoder.Encode(data)
    if err != nil {
       return empty, err
    }
    return buffer.String(), nil
}
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))
}

看起来如何

//You can do it with json.MarshalIndent(data, "", "  ")

package main

import(
  "fmt"
  "encoding/json" //Import package
)

//Create struct
type Users struct {
    ID   int
    NAME string
}

//Asign struct
var user []Users
func main() {
 //Append data to variable user
 user = append(user, Users{1, "Saturn Rings"})
 //Use json package the blank spaces are for the indent
 data, _ := json.MarshalIndent(user, "", "  ")
 //Print json formatted
 fmt.Println(string(data))
}

A simple off the shelf pretty printer in Go.一个简单的现成漂亮的 Go 打印机。 One can compile it to a binary through:可以通过以下方式将其编译为二进制文件:

go build -o jsonformat jsonformat.go

It reads from standard input, writes to standard output and allow to set indentation:它从标准输入读取,写入标准输出并允许设置缩进:

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)
    }
}

It allows to run a bash commands like:它允许运行 bash 命令,例如:

cat myfile | jsonformat | grep "key"

i am sort of new to go, but this is what i gathered up so far:我有点陌生,但这是我到目前为止收集的内容:

package srf

import (
    "bytes"
    "encoding/json"
    "os"
)

func WriteDataToFileAsJSON(data interface{}, filedir string) (int, error) {
    //write data as buffer to json encoder
    buffer := new(bytes.Buffer)
    encoder := json.NewEncoder(buffer)
    encoder.SetIndent("", "\t")

    err := encoder.Encode(data)
    if err != nil {
        return 0, err
    }
    file, err := os.OpenFile(filedir, os.O_RDWR|os.O_CREATE, 0755)
    if err != nil {
        return 0, err
    }
    n, err := file.Write(buffer.Bytes())
    if err != nil {
        return 0, err
    }
    return n, nil
}

This is the execution of the function, and just standard这是函数的执行,只是标准的

b, _ := json.MarshalIndent(SomeType, "", "\t")

Code:代码:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"

    minerals "./minerals"
    srf "./srf"
)

func main() {

    //array of Test struct
    var SomeType [10]minerals.Test

    //Create 10 units of some random data to write
    for a := 0; a < 10; a++ {
        SomeType[a] = minerals.Test{
            Name:   "Rand",
            Id:     123,
            A:      "desc",
            Num:    999,
            Link:   "somelink",
            People: []string{"John Doe", "Aby Daby"},
        }
    }

    //writes aditional data to existing file, or creates a new file
    n, err := srf.WriteDataToFileAsJSON(SomeType, "test2.json")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("srf printed ", n, " bytes to ", "test2.json")

    //overrides previous file
    b, _ := json.MarshalIndent(SomeType, "", "\t")
    ioutil.WriteFile("test.json", b, 0644)

}

Another example with http.ResponseWriter .另一个例子是http.ResponseWriter

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

func main() {
    var w http.ResponseWriter

    type About struct {
        ProgName string
        Version string
    }
    goObj := About{ProgName: "demo", Version: "0.0.0"}
    beautifulJsonByte, err := json.MarshalIndent(goObj, "", "  ")
    if err != nil {
        panic(err)
    }
    _, _ = w.Write(beautifulJsonByte)
}

output输出

{
  "ProgName": "demo",
  "Version": "0.0.0"
}

去游乐场

If you want to create a commandline utility to pretty print JSON如果你想创建一个命令行实用程序来漂亮地打印 JSON


package main

import ("fmt"
  "encoding/json"
  "os"
  "bufio"
  "bytes"
)


func main(){

    var out bytes.Buffer

    reader := bufio.NewReader(os.Stdin)
    text, _ := reader.ReadString('\n')

    err := json.Indent(&out, []byte(text), "", "  ")
    if err != nil {
      fmt.Println(err)
    }

    fmt.Println(string(out.Bytes()))
}

echo "{\"boo\":\"moo\"}" | go run main.go 

will produce the following output :将产生以下输出:

{
  "boo": "moo"
}

feel free to build a binary随意构建一个二进制文件

go build main.go

and drop it in /usr/local/bin并将其放入/usr/local/bin

Use json.MarshalIndent with stringjson.MarshalIndentstring一起使用

This easyPrint function accepts argument data (any type of data) to print it into the intended (pretty) JSON format.这个easyPrint函数接受参数data (任何类型的数据)以将其打印成预期的(漂亮的)JSON 格式。

import (
  "encoding/json"
  "log"
)

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

  log.Println(string(manifestJson))
}

With name argument.name参数。

TODO: make argument name optional. TODO:使参数name可选。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM