chiachan
chiachan
Published on 2022-03-21 / 816 Visits
0

go语言优雅打印json、struct结构

#go

优雅打印json字符串

func TestPrettyJSON(t *testing.T) {
    str := `{"a":1,"b":"s"}`
    var prettyJSON bytes.Buffer
    json.Indent(&prettyJSON, ([]byte)(str), "", "\t")
    t.Logf("%v", string(prettyJSON.Bytes()))
}

优雅打印struct

func TestPrettyStruct(t *testing.T) {
    args := struct {
        A int    `json:"a,omitempty"`
        B string `json:"b,omitempty"`
    }{
        A: 1,
        B: "s",
    }
    body, _ := json.Marshal(args)
    var prettyJSON bytes.Buffer
    json.Indent(&prettyJSON, body, "", "\t")
    t.Logf("%v", string(prettyJSON.Bytes()))
}

封装

package test

import (
	"bytes"
	"encoding/json"
	"golang.org/x/exp/rand"
	"sync"
	"testing"
)

func TestPrettyJSON(t *testing.T) {
	str := `{"a":1,"b":"s"}`
	t.Logf("%v", PrettyJSONString(str))
}

func TestPrettyStruct(t *testing.T) {
	args := struct {
		A int    `json:"a,omitempty"`
		B string `json:"b,omitempty"`
	}{
		A: 1,
		B: "s",
	}
	t.Logf("%v", PrettyStruct(args))
}

func PrettyJSONString(s string) string {
	var prettyJSON bytes.Buffer
	json.Indent(&prettyJSON, ([]byte)(s), "", "\t")
	return string(prettyJSON.Bytes())
}

func PrettyStruct(s interface{}) string {
	body, _ := json.Marshal(s)
	var prettyJSON bytes.Buffer
	json.Indent(&prettyJSON, body, "", "\t")
	return string(prettyJSON.Bytes())
}