Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading