增加控制台格式化输出json

This commit is contained in:
白茶清欢 2021-11-05 18:19:22 +08:00
parent eaa37708c7
commit 43bd254dde

View File

@ -10,7 +10,10 @@ package util
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"os"
"reflect"
) )
// JSONUnmarshalWithNumber 解析json // JSONUnmarshalWithNumber 解析json
@ -34,3 +37,55 @@ func JSONUnmarshalWithNumberForIOReader(ioReader io.ReadCloser, receiver interfa
decoder.UseNumber() decoder.UseNumber()
return decoder.Decode(receiver) return decoder.Decode(receiver)
} }
// JSONConsoleOutput ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 5:45 下午 2021/11/5
func JSONConsoleOutput(data interface{}) {
var out bytes.Buffer
switch reflect.TypeOf(data).Kind() {
case reflect.Slice:
fallthrough
case reflect.Array:
fallthrough
case reflect.Map:
fallthrough
case reflect.Ptr:
byteData, _ := json.Marshal(data)
_ = json.Indent(&out, []byte(string(byteData)+"\n"), "", "\t")
_, _ = out.WriteTo(os.Stdout)
return
case reflect.Int:
fallthrough
case reflect.Int8:
fallthrough
case reflect.Int16:
fallthrough
case reflect.Int32:
fallthrough
case reflect.Int64:
fallthrough
case reflect.Uint:
fallthrough
case reflect.Uint8:
fallthrough
case reflect.Uint16:
fallthrough
case reflect.Uint32:
fallthrough
case reflect.Uint64:
fallthrough
case reflect.Float32:
fallthrough
case reflect.Float64:
fallthrough
case reflect.String:
_ = json.Indent(&out, []byte(fmt.Sprintf("%v\n", data)), "", "\t")
_, _ = out.WriteTo(os.Stdout)
return
default:
fmt.Println("")
}
}