React Native
JSON parse
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.
Exercise 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).
Show example solution
async function loadUser() {
const response = await fetch("https://api.example.com/users/1");
const data = await response.json();
console.log(data.name);
}
Test yourself
-
What does response.json() return?
const data = await response.json();
- String
- Number
- Promise
- Boolean
Show answer
Promise — response.json() returns a Promise; this is why it is awaited.
-
Write the response.json() call
const data = await ____;
Show answer
const data = await response.json();
-
Match the concept to its role
- response.json()
- Parses JSON
- data.name
- Field access
- await
- Waits for a Promise
- Response
- Raw response
Next lesson: Error handling