Skip to content

Support custom JSON parser #254

@kirillgroshkov

Description

@kirillgroshkov

In our codebase (that we're migrating to ky) we use a "JSON reviver" (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse), which works like this:

const parsed = JSON.parse(myJson, myReviver)

I don't see that ky supports it.

I did a workaround (that looks ugly) now via afterResponseHook:

const afterResponseHook: AfterResponseHook = async (_req, _opt, res) => {
  if (!res.ok) return   
  // Parse with JSON Reviver (if possible)   
  const data = JSON.parse(await res.text(), backendResponseReviver)

  // Weird, but pack the "revived" json object back to string, so it can be parsed without reviver then :)
  return new Response(JSON.stringify(data, backendResponseReviver), res)
}

Nicer API would be (for example; not certain about the naming of json() options):

const response = await ky.get(url).json({ reviver: myReviver })

What do you think?

I can try to submit a PR if you think it's a feasible approach.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthelp wantedExtra attention is needed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions