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:
encode calls defaultWriter.reset(), preventing nested calls to encode()
- 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?
I want
encode()to apply the same logic asJSON.stringify(): if the input is an object that has atoJSONfunction; call it and use the returned value for encoding, as specified in the ecmascript spec.I tried adding a special logic in
typeEncoders.Object:But I have several issues:
encodecallsdefaultWriter.reset(), preventing nested calls toencode()Objectcustom encoder, so that thetoJSONis called only once (if the object returned the first time also has atoJSONmethod)How do you suggest I go about doing this?