Fetch json and parse result multiple and single result

Hello,

I’m trying to fetch json with plain javascript and parse the result which is working fine with the foreach when the result is an array response.

        fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => {

data.forEach(function(item) {
 //fine when array
});

  console.log(data)
})

But if we change the url to https://jsonplaceholder.typicode.com/users/1 then there is no array result just a single item result, forEach will fail. How could i build this to handle both single and multiple results, do i really need to check if the result is an array first?

Hi @ptim, technically you might iterate over both arrays and plain objects likewise using Object.keys(), or a for...in or for...of loop. But practically you’ll certainly want to handle user list requests and single user requests differently anyway…

If your URLs return different data types that is by far the most simple option.

For processing it would make sense to then wrap the single object into an array, so you have an array for both cases.

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