How to return "res" as a JSON response

The following code fetches data from my KV namespace and I want it to return a JSON response

const posts = async request => {
		const list = await KV.list(); 
		let res = [];
		for (let key of list.keys){
	  		const value = await KV.get(key.name); 
	  		res.push(value)}
		return new Response(res);
}

Currently, when I console.log(res), the result looks like
{value1}, {value2},{value3}... rather than [{value1}, {value2},{value3}...] as I wanted. What can I do to achieve the latter?

You will want to stringify the array like so:

new Response(JSON.stringify(res), { headers: { 'Content-Type': 'application/json' } });
1 Like

This made the response ["{value1}", "{value2}","{value3}"...]… How do I make it [{value1}, {value2},{value3}...]?

Oh your fetching the keys as strings currently not JSON objects, ok, slight change:

const posts = async request => {
  const list = await KV.list(); 
  let res = [];
  for (let key of list.keys){
    const value = await KV.get(key.name, { type: 'json' }); // Specify JSON as the type
    res.push(value)
  }
  new Response(JSON.stringify(res), { headers: { 'Content-Type': 'application/json' } });
}
3 Likes

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.