Sveltekit Actions returns garbled json

json returned from a Sveltekit actions is garbled. I would expect something like this:

{ foo: bar, foo2: bar2 }

But instead I get this:

Array({ foo: 1, foo2: 2 }, bar, bar2)

Which is even more annoying with nested data.

This is how I send it:

const response = await fetch('/api/fetch', {
  method: 'POST'
}).then((res) => {
  res.json().then((r) => {
    console.log(JSON.parse(r.data))
  })
})

This is api/fetch/+page.server.js

export const actions = {
  default: async ({ request }) => {
    const response = await fetch(
      'https://exterual-url-that-returns-json', {
        method: 'GET'
      }
    )
    return await response.json()
  }
}

I have the same problem even if the json object is not fetched from an external url, i.e. return { foo: bar, foo2: bar2 }

>Solution :

The JSON is not garbled but serialized via devalue which has fewer limitations than plain JSON.stringify, e.g. it retains Date, Set and Map objects.

The JSON is supposed to be consumed by SvelteKit code which should automatically convert it correctly. Actions are supposed to be used with <form> elements and the result is passed to the page in a form property; to process the request asynchronously, use the enhance action.

If you for some reason have to process the data manually, use the deserialize from $app/forms.

Leave a Reply