Skip to content

Add support for toJSON() #173

Description

@matthieusieben

I want encode() to apply the same logic as JSON.stringify(): if the input is an object that has a toJSON function; call it and use the returned value for encoding, as specified in the ecmascript spec.

I tried adding a special logic in typeEncoders.Object:

      if ('toJSON' in obj && typeof (obj as any).toJSON === 'function') {
        const value = (obj as any).toJSON()
        const encoded = encode(value, encodeOptions)
        return [new Token(Type.map, encoded)]
      }

But I have several issues:

  1. encode calls defaultWriter.reset(), preventing nested calls to encode()
  2. I need to avoid infinite loops, which means that I have to use two different versions of Object custom encoder, so that the toJSON is called only once (if the object returned the first time also has a toJSON method)

How do you suggest I go about doing this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions