JavaScript: response.json()
The response.json() method parses a JSON response body into a JavaScript object or array.
What you will learn
- How
response.json()converts a JSON body - How to return its Promise to the next
.then() - How to handle invalid JSON or network failures with
.catch()
Minimal example
fetch("data.json")
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(data => {
console.log("Parsed data:", data);
})
.catch(error => {
console.error("Could not read JSON:", error);
});response.json() returns a Promise because reading and parsing the body takes time. Returning it makes the parsed object or array available to the next callback.
Important points
- The response body must contain valid JSON, or parsing rejects the returned Promise.
- Check
response.okbefore parsing when HTTP errors should be handled explicitly. - A response body is normally consumed once; choose
json()ortext()based on the format you need.