Skip to content

feature: Support JSON Tag 262? #657

Closed
@theory

Description

@theory

Is your feature request related to a problem? Please describe.

I inquired with the CBOR mail list about adding a tag for JSON numbers as string, toward having an official tag number to use for the pattern I posted in #441. They suggested that tag 262, an embedded JSON value, might also apply. However, since encoding/json values into any except for json.Number resolve to core Go types, and will vary, I can't see a clear way to register 262 with TagSet.Add.

Describe the solution you'd like

Either formal support for tag 262 or else some sort of way to register a tag that resolves to more than one type.

Describe alternatives you've considered

I tried to create a JSON type that wraps JSON values:

type JSON struct {
	any
}

func NewJSON(val any) JSON { return JSON{val} }

func (jt JSON) MarshalCBOR() ([]byte, error) {
	data, err := jt.MarshalJSON()
	if err != nil {
		return nil, err
	}
	return cbor.RawTag{Number: 262, Content: data}.MarshalCBOR()
}

func (jt *JSON) UnmarshalCBOR(b []byte) error {
	var tag cbor.RawTag
	if err := cbor.Unmarshal(b, &tag); err != nil {
		return err
	}
	return jt.UnmarshalJSON(tag.Content)
}

func (jt JSON) MarshalJSON() ([]byte, error) {
	return json.Marshal(jt.any)
}

func (jt *JSON) UnmarshalJSON(b []byte) error {
	enc := json.NewDecoder(bytes.NewReader(b))
	enc.UseNumber()
	return enc.Decode(&jt.any)
}

However, an attempt to marshal a value of this type fails; I probably don't fully understand the RawTag bit:

func main() {
	user := NewJSON(map[string]any{
		"name": "theory",
		"id":   json.Number("1024"),
	})

	data, err := cbor.Marshal(user)
	if err != nil {
		panic(err)
	}
}

Output:

panic: cbor: error calling MarshalCBOR for type main.JSON: unexpected EOF

Am I on the right track?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions