github.com/chaowen112/go-lib@v0.0.0-20231018124935-124cd26d7cbe/jsonutils/json.go (about)

     1  package json
     2  
     3  import (
     4  	jsoniter "github.com/json-iterator/go" // nolint:goimports
     5  	"github.com/json-iterator/go/extra"
     6  	"github.com/pkg/errors"
     7  )
     8  
     9  // nolint:gochecknoinits
    10  func init() {
    11  	jsoniter.RegisterExtension(&extra.BinaryAsStringExtension{})
    12  }
    13  
    14  var (
    15  	json                = jsoniter.ConfigCompatibleWithStandardLibrary
    16  	Marshal             = json.Marshal
    17  	MarshalIndent       = json.MarshalIndent
    18  	Unmarshal           = json.Unmarshal
    19  	MarshalToString     = json.MarshalToString
    20  	UnmarshalFromString = json.UnmarshalFromString
    21  	NewDecoder          = json.NewDecoder
    22  	NewEncoder          = json.NewEncoder
    23  )
    24  
    25  func DeepCopy(dst interface{}, src interface{}) error {
    26  	srcJSON, err := json.Marshal(src)
    27  	if err != nil {
    28  		return errors.Wrapf(err, "marshal failed when deep copy")
    29  	}
    30  
    31  	err = json.Unmarshal(srcJSON, dst)
    32  	if err != nil {
    33  		return errors.Wrapf(err, "unmarshal failed when deep copy")
    34  	}
    35  
    36  	return nil
    37  }
    38  
    39  func MarshalPretty(v interface{}) ([]byte, error) {
    40  	return MarshalIndent(v, "", "    ")
    41  }