We use JSON response parsing to read data sent from a server in a format our app can understand and use.
0
0
JSON response parsing in React Native
Introduction
When your app gets data from the internet, like user info or messages.
When you want to show updated content without changing the app code.
When you connect to online services like weather or news APIs.
When you save and load app settings or data in JSON format.
When you want to handle responses from a backend after sending data.
Syntax
React Native
fetch('https://example.com/data')
.then(response => response.json())
.then(data => {
// use the parsed data here
})
.catch(error => {
// handle errors here
});fetch gets data from a URL.
response.json() converts the response to a JavaScript object.
Examples
This fetches a list of users and prints it to the console.
React Native
fetch('https://api.example.com/users')
.then(res => res.json())
.then(users => console.log(users));This uses async/await to get and parse JSON data cleanly.
React Native
async function getData() { const response = await fetch('https://api.example.com/data'); const jsonData = await response.json(); console.log(jsonData); }
Sample App
This React Native app fetches a todo item from a test API, parses the JSON response, and shows the todo details on screen. It also shows a loading spinner while waiting and an error message if something goes wrong.
React Native
import React, { useState, useEffect } from 'react'; import { View, Text, ActivityIndicator } from 'react-native'; export default function App() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(json => { setData(json); setLoading(false); }) .catch(err => { setError(err.message); setLoading(false); }); }, []); if (loading) return <ActivityIndicator size="large" />; if (error) return <Text>Error: {error}</Text>; return ( <View style={{ padding: 20 }}> <Text>Todo ID: {data.id}</Text> <Text>Title: {data.title}</Text> <Text>Completed: {data.completed ? 'Yes' : 'No'}</Text> </View> ); }
OutputSuccess
Important Notes
Always handle errors when fetching data to avoid app crashes.
Use loading indicators to improve user experience while waiting for data.
JSON parsing turns text data into objects you can use in your app.
Summary
JSON response parsing lets your app understand data from servers.
Use fetch and response.json() to get and parse JSON.
Handle loading and errors for smooth app behavior.