How to Get JSON from fetch() in JavaScript


How can we obtain the JSON from a URL using the Fetch API?

The Fetch API returns a Response object in the promise.

In order to parse a JSON response, we need to use response.json(), which also returns a promise.

We can use async/await to handle the promises.

const res = await fetch('http://jsonplaceholder.typicode.com/todos');
const json = await res.json();
console.log(json);

Or, we can chain multiple then() handlers.

fetch('http://jsonplaceholder.typicode.com/todos')
.then(res => res.json())
.then(json => console.log(json));

Read more about the Response object.