Paramclasses Academy - Blog

Tutorials Details

←
Post 22 of 39
→

How to use JSON Parsing in React Native: Display API Data in Your App ?

How to use JSON Parsing in React Native: Display API Data in Your App ?

November 5, 2026

1. Introduction

JSON is one of the most important data formats used in modern mobile applications.

Whenever a React Native application communicates with a backend server, it commonly receives information in JSON format.

For example:

  • A student application receives student records.

  • A shopping application receives product details.

  • A news application receives articles.

  • A social media application receives user profiles and posts.

In this tutorial, we will understand JSON step by step and build a practical Student Management Application.

We will learn:

  1. What JSON is.

  2. JSON objects and arrays.

  3. JSON parsing.

  4. JSON.stringify().

  5. JSON.parse().

  6. Fetching JSON data from an API.

  7. Displaying JSON data using FlatList.

  8. Accessing nested JSON objects.

  9. Handling JSON errors.

  10. Sending JSON data to a backend.

2. What Is JSON?

JSON stands for JavaScript Object Notation.

It is a lightweight data format used to exchange information between applications and servers.

Example:

{
  "id": 1,
  "name": "Rahul Sharma",
  "email": "rahul@gmail.com",
  "course": "React Native"
}

This JSON object contains four properties:

  • id: Student ID.

  • name: Student name.

  • email: Student email.

  • course: Course name.

JSON is easy to read and is supported by almost every modern programming language.

3. Understanding JSON Data Types

JSON supports the following data types:

A. String

{
  "name": "Rahul Sharma"
}

B. Number

{
  "age": 22,
  "marks": 85
}

C. Boolean

{
  "isActive": true
}

Boolean values can be true or false.

D. Array

{
  "subjects": [
    "JavaScript",
    "React Native",
    "PHP"
  ]
}

An array stores multiple values.

E. Object

{
  "student": {
    "name": "Rahul",
    "city": "Raipur"
  }
}

An object can contain another object.

F. Null

{
  "address": null
}

Null represents an intentionally empty value.

4. What Is JSON Parsing?

JSON parsing means converting JSON text into a JavaScript value that we can work with in our application.

For example, consider this JSON string:

const jsonData = '{"name":"Rahul","age":22}';

This is a string, not yet a JavaScript object.

To convert it into an object, we use:

const student = JSON.parse(jsonData);

console.log(student.name);
console.log(student.age);

Output:

Rahul
22

The JSON.parse() method converts valid JSON text into a JavaScript value.

5. What Is JSON.stringify()?

JSON.stringify() performs the opposite operation.

It converts a JavaScript value into a JSON-formatted string.

Example:

const student = {
  name: "Rahul",
  age: 22,
  course: "React Native"
};

const jsonData = JSON.stringify(student);

console.log(jsonData);

Output:

{"name":"Rahul","age":22,"course":"React Native"}

Difference Between JSON.parse() and JSON.stringify()

Method Purpose
JSON.parse() JSON string to JavaScript value
JSON.stringify() JavaScript value to JSON string

Remember:

  • JSON.parse() reads JSON text.

  • JSON.stringify() creates JSON text.

6. What Is the Difference Between response.json() and JSON.parse()?

This is an important concept.

response.json()

When using Fetch API, we commonly write:

const response = await fetch(
  "https://jsonplaceholder.typicode.com/users"
);

const data = await response.json();

response.json() reads the response body and parses it into a JavaScript value.

JSON.parse()

Use JSON.parse() when you already have JSON text as a string.

const jsonString = '{"name":"Rahul"}';

const data = JSON.parse(jsonString);

console.log(data.name);

Important: Do not write JSON.parse() on an object that has already been parsed. It expects JSON text, not an ordinary JavaScript object.

7. Create a React Native Project

Now we will create a practical Student Management Application.

Open your terminal:

npx create-expo-app@latest StudentJsonApp --template blank

Navigate into the project:

cd StudentJsonApp

Open Visual Studio Code:

code .

Start the application:

npx expo start

Run the application using Expo Go or an Android emulator.

8. Understand Our API Response

We will use the JSONPlaceholder testing API.

API URL:

https://jsonplaceholder.typicode.com/users

This endpoint returns a JSON array containing user records.

A simplified example of one record:

{
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "leanne@example.com",
  "address": {
    "street": "Kulas Light",
    "city": "Gwenborough",
    "zipcode": "92998-3874"
  },
  "phone": "1-770-736-8031",
  "website": "hildegard.org"
}

Notice that address is another object inside the main object.

This is called a nested JSON object.

9. Fetch JSON Data in React Native

Open App.js.

Step 1: Import Required Components

import React, { useEffect, useState } from "react";

import {
  View,
  Text,
  StyleSheet,
  FlatList,
  ActivityIndicator,
} from "react-native";

Explanation:

  • useState stores API records.

  • useEffect triggers the API request.

  • FlatList displays multiple records.

  • ActivityIndicator shows loading progress.

Step 2: Create State Variables

Inside the App component:

const [students, setStudents] = useState([]);

const [loading, setLoading] = useState(true);

const [error, setError] = useState("");

Explanation:

  • students stores parsed JSON records.

  • loading manages the loading screen.

  • error stores an error message.

Step 3: Fetch API Data

Create the following function:

const fetchStudents = async (signal) => {

  try {

    setLoading(true);
    setError("");

    const response = await fetch(
      "https://jsonplaceholder.typicode.com/users",
      { signal }
    );

    if (!response.ok) {
      throw new Error("API request failed");
    }

    const jsonData = await response.json();

    setStudents(jsonData);

  } catch (error) {

    if (error.name !== "AbortError") {
      setError(error.message);
    }

  } finally {

    if (!signal?.aborted) {
      setLoading(false);
    }

  }

};

Let's understand the important lines.

1. Fetch API request

const response = await fetch(
  "https://jsonplaceholder.typicode.com/users",
  { signal }
);

This sends a request to the server.

2. Check the response

if (!response.ok) {
  throw new Error("API request failed");
}

This checks whether the HTTP response indicates success.

3. Parse JSON data

const jsonData = await response.json();

This converts the response body into a JavaScript array of objects.

4. Store the data

setStudents(jsonData);

This saves the parsed records in React state.

10. Call the API Using useEffect()

Add this inside the App component:

useEffect(() => {

  const controller = new AbortController();

  fetchStudents(controller.signal);

  return () => {
    controller.abort();
  };

}, []);

Explanation:

  • useEffect() runs after the component mounts.

  • The API function is called automatically.

  • AbortController allows the request to be cancelled during cleanup.

  • The empty dependency array prevents repeated requests caused by ordinary re-renders.

11. Access JSON Object Properties

Suppose we receive this object:

const student = {
  id: 1,
  name: "Rahul Sharma",
  email: "rahul@gmail.com",
  address: {
    city: "Raipur",
    state: "Chhattisgarh"
  }
};

We can access its values using dot notation.

console.log(student.name);

console.log(student.email);

console.log(student.address.city);

console.log(student.address.state);

Output:

Rahul Sharma
rahul@gmail.com
Raipur
Chhattisgarh

To access nested data, use the parent property followed by the child property.

12. Display JSON Array Data Using FlatList

Our API returns multiple user records in an array.

We can display them using FlatList.

Example:

<FlatList

  data={students}

  keyExtractor={(item) =>
    item.id.toString()
  }

  renderItem={({ item }) => (

    <View style={styles.card}>

      <Text>{item.name}</Text>

      <Text>{item.email}</Text>

      <Text>{item.address.city}</Text>

    </View>

  )}

/>

Explanation:

  • data receives the parsed JSON array.

  • keyExtractor identifies each record uniquely.

  • renderItem defines how each record appears.

  • item.name accesses the student name.

  • item.address.city accesses nested JSON information.

13. Complete Practical Project: Student JSON App

Now replace the entire App.js file with the following code.

This project will:

  • Connect to a REST API.

  • Receive JSON data.

  • Parse the response.

  • Store records in state.

  • Display student information.

  • Show a loading indicator.

  • Handle API errors.

  • Provide a retry button.

Complete App.js Code

import React, { useEffect, useState } from "react";

import {
  View,
  Text,
  StyleSheet,
  FlatList,
  ActivityIndicator,
  Pressable,
} from "react-native";

export default function App() {

  const [students, setStudents] = useState([]);

  const [loading, setLoading] = useState(true);

  const [error, setError] = useState("");

  const fetchStudents = async (signal) => {

    try {

      setLoading(true);
      setError("");

      const response = await fetch(
        "https://jsonplaceholder.typicode.com/users",
        { signal }
      );

      if (!response.ok) {
        throw new Error("Unable to load student records");
      }

      const jsonData = await response.json();

      if (!Array.isArray(jsonData)) {
        throw new Error("Invalid API data format");
      }

      setStudents(jsonData);

    } catch (error) {

      if (error.name !== "AbortError") {
        setError(error.message);
      }

    } finally {

      if (!signal?.aborted) {
        setLoading(false);
      }

    }

  };

  useEffect(() => {

    const controller = new AbortController();

    fetchStudents(controller.signal);

    return () => {
      controller.abort();
    };

  }, []);

  if (loading) {

    return (

      <View style={styles.center}>

        <ActivityIndicator
          size="large"
          color="#2563EB"
        />

        <Text style={styles.loading}>
          Parsing JSON Data...
        </Text>

      </View>

    );

  }

  if (error) {

    return (

      <View style={styles.center}>

        <Text style={styles.error}>
          {error}
        </Text>

        <Pressable
          style={styles.button}
          onPress={() => fetchStudents()}
        >

          <Text style={styles.buttonText}>
            Retry
          </Text>

        </Pressable>

      </View>

    );

  }

  return (

    <View style={styles.container}>

      <Text style={styles.heading}>
        Student Management
      </Text>

      <Text style={styles.subtitle}>
        JSON API Records
      </Text>

      <FlatList

        data={students}

        keyExtractor={(item) =>
          item.id.toString()
        }

        renderItem={({ item }) => (

          <View style={styles.card}>

            <Text style={styles.name}>
              {item.name}
            </Text>

            <Text style={styles.info}>
              ID: {item.id}
            </Text>

            <Text style={styles.info}>
              Username: {item.username}
            </Text>

            <Text style={styles.info}>
              Email: {item.email}
            </Text>

            <Text style={styles.info}>
              City: {item.address?.city ?? "Not available"}
            </Text>

            <Text style={styles.info}>
              Phone: {item.phone}
            </Text>

          </View>

        )}

        ListEmptyComponent={
          <Text style={styles.empty}>
            No student records found.
          </Text>
        }

      />

    </View>

  );

}

const styles = StyleSheet.create({

  container: {
    flex: 1,
    backgroundColor: "#F1F5F9",
    padding: 20,
    paddingTop: 55,
  },

  center: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    padding: 20,
  },

  heading: {
    fontSize: 25,
    fontWeight: "bold",
    color: "#1E293B",
  },

  subtitle: {
    fontSize: 14,
    color: "#64748B",
    marginTop: 5,
    marginBottom: 20,
  },

  loading: {
    marginTop: 12,
    color: "#334155",
  },

  card: {
    backgroundColor: "#FFFFFF",
    padding: 16,
    marginBottom: 14,
    borderRadius: 12,
    elevation: 3,
  },

  name: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#2563EB",
    marginBottom: 8,
  },

  info: {
    fontSize: 14,
    color: "#475569",
    marginTop: 4,
  },

  error: {
    color: "#DC2626",
    fontSize: 16,
    marginBottom: 15,
    textAlign: "center",
  },

  button: {
    backgroundColor: "#2563EB",
    padding: 12,
    borderRadius: 8,
  },

  buttonText: {
    color: "#FFFFFF",
    fontWeight: "bold",
  },

  empty: {
    textAlign: "center",
    color: "#64748B",
    marginTop: 30,
  },

});

14. Understand JSON.stringify() in POST Requests

Now we will understand how to send JSON data from React Native to a backend server.

Suppose we want to send a new student record.

const student = {

  name: "Amit Sharma",

  email: "amit@gmail.com",

  course: "React Native"

};

We need to convert this JavaScript object into a JSON string.

const jsonData = JSON.stringify(student);

console.log(jsonData);

Now send the data using Fetch:

const saveStudent = async () => {

  try {

    const response = await fetch(
      "https://jsonplaceholder.typicode.com/users",
      {
        method: "POST",

        headers: {
          "Content-Type": "application/json",
        },

        body: JSON.stringify({
          name: "Amit Sharma",
          email: "amit@gmail.com",
          course: "React Native",
        }),

      }
    );

    if (!response.ok) {
      throw new Error("Failed to send student data");
    }

    const result = await response.json();

    console.log(result);

  } catch (error) {

    console.log(error.message);

  }

};

Important points:

  • method: "POST" sends a new record.

  • Content-Type tells the server that we are sending JSON.

  • JSON.stringify() converts the object into JSON text.

  • response.json() parses the server's response.

JSONPlaceholder is a demonstration API. It simulates creation requests and does not permanently save the new student.

15. Handle Invalid JSON Data

Sometimes an application receives invalid JSON text.

Example:

const jsonData = '{"name":"Rahul",}';

This string contains invalid JSON because of the extra comma.

We can handle such errors using try/catch.

try {

  const student = JSON.parse(jsonData);

  console.log(student.name);

} catch (error) {

  console.log("Invalid JSON Format");

}

This prevents an invalid JSON string from crashing the relevant operation without error handling.

16. Common JSON Parsing Mistakes

Mistake 1: Parsing an already parsed object

Incorrect:

const data = await response.json();

const student = JSON.parse(data);

Correct:

const data = await response.json();

Mistake 2: Accessing an incorrect property

Incorrect:

item.address.cityName

Correct:

item.address.city

Always inspect the actual API response.

Mistake 3: Forgetting to convert objects into JSON strings

Incorrect:

body: student

Correct:

body: JSON.stringify(student)

Mistake 4: Ignoring null values

Incorrect:

item.address.city

Safer:

item.address?.city ?? "Not available"

Mistake 5: Not handling invalid responses

Always check HTTP status, validate the expected data structure, and handle parsing errors.

17. Practical Exercises

Complete these exercises:

  1. Fetch all users from JSONPlaceholder.

  2. Display student names using FlatList.

  3. Display student email addresses.

  4. Display nested city information.

  5. Display usernames and phone numbers.

  6. Retrieve a single record using /users/1.

  7. Convert a JavaScript object using JSON.stringify().

  8. Convert JSON text using JSON.parse().

  9. Handle invalid JSON using try/catch.

  10. Send a POST request with student information.

18. Best Practices

  • Understand the API response structure before accessing properties.

  • Use response.json() to parse Fetch response bodies.

  • Use JSON.parse() only when working with JSON text.

  • Use JSON.stringify() when creating JSON request bodies.

  • Validate API response structures.

  • Handle missing and null properties.

  • Use FlatList for large data collections.

  • Handle network and parsing errors.

  • Never assume that the API will always return the expected data.

  • Avoid exposing private credentials in application code.

19. Conclusion

In this tutorial, we learned how JSON works in React Native and how applications process structured information received from a backend server.

We covered:

  • JSON fundamentals.

  • JSON objects and arrays.

  • JSON data types.

  • JSON.parse().

  • JSON.stringify().

  • response.json().

  • Nested JSON objects.

  • REST API integration.

  • FlatList data rendering.

  • POST requests.

  • JSON error handling.

We also built a practical Student Management Application that retrieves JSON data and displays it inside a mobile application.

JSON parsing is an essential skill for connecting React Native applications with PHP, MySQL, Firebase and other backend technologies.

20. Frequently Asked Questions

Q1. What is JSON in React Native?

JSON is a data format used to exchange structured information between React Native applications and backend servers.

Q2. What is JSON.parse()?

It converts valid JSON text into a JavaScript value.

Q3. What is JSON.stringify()?

It converts a JavaScript value into a JSON-formatted string.

Q4. What does response.json() do?

It reads the Fetch response body and parses it into a JavaScript value.

Q5. Can JSON contain arrays and objects together?

Yes. JSON supports nested objects and arrays.

Q6. How do we access nested JSON data?

Use dot notation or optional chaining, such as student.address.city or student.address?.city.

Q7. Can React Native send JSON data to PHP?

Yes. React Native can send JSON request bodies to PHP REST API endpoints using Fetch or Axios.

Q8. What happens if JSON is invalid?

JSON.parse() throws an error. Use try/catch to handle invalid JSON safely.

Q9. Can we display JSON arrays using FlatList?

Yes. Pass the array to FlatList through its data property and define renderItem.

Q10. Is JSON the same as JavaScript objects?

No. JSON is a text-based data format, while JavaScript objects are in-memory programming values. JSON must be parsed before being used as an ordinary JavaScript object.

←
Post 22 of 39
→