gopkg/util/json.go

92 lines
1.9 KiB
Go
Raw Normal View History

2021-09-14 20:45:35 +08:00
// Package util...
//
// Description : json 工具函数
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2021-09-14 8:38 下午
package util
import (
"bytes"
"encoding/json"
2021-11-05 18:19:22 +08:00
"fmt"
2021-09-14 20:45:35 +08:00
"io"
2021-11-05 18:19:22 +08:00
"os"
"reflect"
2021-09-14 20:45:35 +08:00
)
// JSONUnmarshalWithNumber 解析json
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 8:39 下午 2021/9/14
func JSONUnmarshalWithNumber(byteData []byte, receiver interface{}) error {
decoder := json.NewDecoder(bytes.NewReader(byteData))
decoder.UseNumber()
return decoder.Decode(receiver)
}
// JSONUnmarshalWithNumberForIOReader ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 8:43 下午 2021/9/14
func JSONUnmarshalWithNumberForIOReader(ioReader io.ReadCloser, receiver interface{}) error {
decoder := json.NewDecoder(ioReader)
decoder.UseNumber()
return decoder.Decode(receiver)
}
2021-11-05 18:19:22 +08:00
// 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("")
}
}