Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle json.RawMessage or introduce a similar type #425

Open
nieomylnieja opened this issue Feb 3, 2024 · 0 comments
Open

Handle json.RawMessage or introduce a similar type #425

nieomylnieja opened this issue Feb 3, 2024 · 0 comments

Comments

@nieomylnieja
Copy link
Contributor

Is your feature request related to a problem? Please describe.
When decoding models that support both JSON and YAML encoding, it's convenient that we already support json tags for YAML, but when using json.RawMessage go-yaml does not handle it.
Due to that there's no native (from go-yaml perspective) way to handle such models.
Converting from YAML to JSON is not an option for me as I want to retain separate syntax errors for JSON and YAML.

Describe the solution you'd like
We should either handle json.RawMessage type or introduce a new type, like yaml.RawMessage which could implement both json.(Un)marshaler and yaml.Bytes(Un)marshaler interfaces.

Describe alternatives you've considered
Currently I've implemented my own type for that.
Having to redefine it in every project I work with though is not ideal.

package serdeutil

import "github.com/pkg/errors"

// RawMessage is a raw encoded JSON or YAML value.
// It implements:
// - [json.Marshaler] and [json.Unmarshaler]
// - [yaml.BytesMarshaler] and [yaml.BytesUnmarshaler]
// It can be used to delay JSON/YAML decoding or precompute a JSON/YAML encoding.
type RawMessage []byte

func (m RawMessage) MarshalJSON() ([]byte, error) { return m.marshal() }
func (m RawMessage) MarshalYAML() ([]byte, error) { return m.marshal() }

func (m RawMessage) marshal() ([]byte, error) {
	if m == nil {
		return []byte("null"), nil
	}
	return m, nil
}

func (m *RawMessage) UnmarshalJSON(data []byte) error { return m.unmarshal(data) }
func (m *RawMessage) UnmarshalYAML(data []byte) error { return m.unmarshal(data) }

func (m *RawMessage) unmarshal(data []byte) error {
	if m == nil {
		return errors.New("RawMessage: unmarshal on nil pointer")
	}
	*m = append((*m)[0:0], data...)
	return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant