JSON.stringify replacer option
Related: https://github.com/honojs/hono/issues/1096. Not sure why the author closed the original issue as completed. Also not sure about your stance on discussions in closed issues so opening a new one
What is the feature you are proposing?
I think having a custom JSON.stringify option available would be beneficial.
Currently I sometimes have to do either
-
c.json(JSON.parse(jsonStringify(obj) as typeof obj), 200) // note: `as typeof obj` to not lose typeswhich introduces overhead since Hono will make another
JSON.stringifypass internally, or -
c.text(jsonStrinfiy(obj), 200, { "Content-Type": "application/json" })which isn't the most ergonomic to type (and also loses typed response)
as workarounds
I'm thinking as an initialization option when initializing the Hono app, we can pass a custom stringifier
const app = new Hono({
jsonStringify: jsonStringify
})
that would then be used here: https://github.com/honojs/hono/blob/bdaaa7fef81371ddb2a4cbb156dff5221d8cc8c5/src/context.ts#L829
A possible footgun migth be that the replacer function could change the types, but so could the normal JSON.stringify, e.g.
c.json({ num: Infinity }) // response typed as { num: number } but Inifinity serializes to `null`
which a safe number replacer could "fix" by replacing Infinity with Number.MAX_SAFE_INTEGER depending on the application
Hi @juliusmarminge
This is related to #1706
Enabling customizing a JSON serializer is a good feature. We must consider whether it can keep the TypeScript types for RPC mode(TypedResponse). We also have to think about the API. I wouldn't say I like passing the serializer function to the construct of Hono since we want to keep the hono-base.ts minimum and don't want to pass many objects to the constructor of Context inside of it.
I'll leave comments if I have a good idea.
@yusukebe
I'll leave comments if I have a good idea.
Just following up to see if any ideas spawned. Our team is looking for a solution to this as well.
Generally this seems to be a common ask (usually around dates) based on #1559, #1800, and #1706
I'm currently using the article you pointed out in #1559 - some tweaks were needed due to changes and it generally works but this is a workaround.
I'll leave comments if I have a good idea.
Just following up to see if any ideas spawned. Our team is looking for a solution to this as well.
Generally this seems to be a common ask (usually around dates) based on #1559, #1800, and #1706
I'm currently using the article you pointed out in #1559 - some tweaks were needed due to changes and it generally works but this is a workaround.
What are those tweaks? I'm having the same issue