JSON parse
- React Native course
- Intermediate
- Lesson 39/116
- 5 min
Learn JSON parsing with response.json().
What is JSON parse?
The Response object returned by fetch carries the raw response; it does not give the data directly. To extract the data you call response.json(). This method parses the response as JSON and turns it into a JavaScript object.
Example: const data = await response.json();. This line waits for the response, parses it as JSON and assigns it to data. data is now a plain JavaScript object; you access fields like data.name. response.json() also returns a Promise; so it must be awaited. JSON is the standard format for data exchange; it consists of key-value pairs. If the response is not JSON, you use response.text().
Using JSON data
The response.json() call returns a JavaScript object. You access its fields with a dot: data.name, data.email. If the response is an array, you access items with an index: data[0].name.
Example API response: { id: 1, name: "Ayşe", email: "ayse@example.com" }. In this object data.name gives "Ayşe". If the response is an array like [{ id: 1, name: "Ayşe" }, { id: 2, name: "Alex" }] then data.length gives 2, data[0].name gives "Ayşe". In React you can put this data into state and show it in the component. It is important to check the data exists before rendering; otherwise you get an undefined error on the first render.
Practice Parse a JSON response
Write an async function loadUser. Assign await fetch("https://api.example.com/users/1") to const response. Assign await response.json() to const data. Call console.log(data.name).
Starter code
// Write async function loadUser
// get response with await fetch
// parse the data and log the name fieldSample solution
async function loadUser() {
const response = await fetch("https://api.example.com/users/1");
const data = await response.json();
console.log(data.name);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does response.json() return?
const data = await response.json();- String
- Number
- Promise Correct answer
- Boolean
Explanation: response.json() returns a Promise; this is why it is awaited.
2 Write the response.json() call
const data = await ____;
const data = await response.json();
Explanation: response.json() parses the response.
3 Match the concept to its role
| Term | Meaning |
|---|---|
response.json() |
Parses JSON |
data.name |
Field access |
await |
Waits for a Promise |
Response |
Raw response |