github.com/Finschia/finschia-sdk@v0.48.1/codec/yaml.go (about)

     1  package codec
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	"github.com/gogo/protobuf/proto"
     7  	"gopkg.in/yaml.v2"
     8  )
     9  
    10  // MarshalYAML marshals toPrint using JSONCodec to leverage specialized MarshalJSON methods
    11  // (usually related to serialize data with protobuf or amin depending on a configuration).
    12  // This involves additional roundtrip through JSON.
    13  func MarshalYAML(cdc JSONCodec, toPrint proto.Message) ([]byte, error) {
    14  	// We are OK with the performance hit of the additional JSON roundtip. MarshalYAML is not
    15  	// used in any critical parts of the system.
    16  	bz, err := cdc.MarshalJSON(toPrint)
    17  	if err != nil {
    18  		return nil, err
    19  	}
    20  
    21  	// generate YAML by decoding JSON and re-encoding to YAML
    22  	var j interface{}
    23  	err = json.Unmarshal(bz, &j)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  
    28  	return yaml.Marshal(j)
    29  }