Lesson 53 of 60 – JSON in React Native
88%

JSON in React Native

JSON stands for JavaScript Object Notation. It is a lightweight text format commonly used for exchanging data between a React Native application and a backend API.

When a React Native application communicates with a server, the server often sends data in JSON format.

React Native App
       ↓
    HTTP Request
       ↓
      API
       ↓
   JSON Response
       ↓
React Native App
Note: JSON is a text-based data format. JSON objects look similar to JavaScript objects, but JSON has its own syntax rules.

1. What is JSON?

JSON is a standard format for representing and exchanging structured data.

A simple JSON object looks like this:

{
    "name": "Rahul",
    "age": 21
}

JSON is commonly used by REST APIs.

2. Why is JSON Used in React Native?

React Native applications often need to exchange data with backend servers.

  • User information
  • Course information
  • Product information
  • Orders
  • Assignments
  • Notifications

JSON provides a common format for transferring this information.

3. Basic JSON Object

A JSON object is enclosed in curly braces.

{
    "name": "Rahul",
    "city": "Patna",
    "age": 21
}

Each property has a key and a value.

4. JSON Keys

JSON keys are written inside double quotation marks.

{
    "name": "Rahul",
    "email": "rahul@example.com"
}

Here, name and email are JSON keys.

5. JSON String Values

String values are written inside double quotation marks.

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

Both "Rahul" and "React Native" are string values.

6. JSON Number Values

Numbers do not need quotation marks in JSON.

{
    "age": 21,
    "fee": 15000
}

Here, 21 and 15000 are numbers.

7. JSON Boolean Values

JSON supports boolean values: true and false.

{
    "isStudent": true,
    "isActive": false
}

Boolean values do not use quotation marks.

8. JSON Null Value

JSON also supports the null value.

{
    "profileImage": null
}

The null value represents the absence of a value.

9. JSON Arrays

An array contains multiple values and is written using square brackets.

{
    "courses": [
        "HTML",
        "CSS",
        "JavaScript"
    ]
}

The courses property contains an array of strings.

10. JSON Array of Objects

A very common API response is an array containing multiple objects.

{
    "students": [

        {
            "id": 1,
            "name": "Rahul"
        },

        {
            "id": 2,
            "name": "Amit"
        }

    ]
}

This structure is frequently used for list data.

11. Nested JSON Objects

A JSON object can contain another JSON object.

{
    "name": "Rahul",

    "address": {
        "city": "Patna",
        "state": "Bihar"
    }
}

The address property contains another object.

12. Accessing JSON Data in JavaScript

After receiving JSON and converting it into a JavaScript value, you can access its properties using dot notation.

const user = {
    name: "Rahul",
    age: 21
};

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

13. Accessing Nested JSON Data

const user = {

    name: "Rahul",

    address: {
        city: "Patna"
    }

};

console.log(
    user.address.city
);

Nested properties can be accessed using multiple property names.

14. JSON.parse()

JSON.parse() converts a JSON string into a JavaScript value.

const jsonString =
    '{"name":"Rahul","age":21}';

const user =
    JSON.parse(jsonString);

console.log(user.name);

This is useful when JSON data is available as a string.

15. JSON.stringify()

JSON.stringify() converts a JavaScript value into a JSON string.

const user = {

    name: "Rahul",
    age: 21

};

const jsonString =
    JSON.stringify(user);

console.log(jsonString);

This is commonly useful when sending JSON data to an API.

16. JSON with Fetch API

Fetch can receive a JSON response from an API.

const response =
    await fetch(url);

const data =
    await response.json();

console.log(data);

The json() method parses the response body as JSON.

17. JSON with Axios

Axios commonly exposes the parsed response body through response.data.

const response =
    await axios.get(url);

console.log(
    response.data
);

This makes working with JSON API responses convenient.

18. Displaying JSON Data in React Native

const user = {
    name: "Rahul",
    course: "React Native"
};

return (

    <View>

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

        <Text>
            {user.course}
        </Text>

    </View>

);

JavaScript object properties can be displayed directly in JSX.

19. Displaying a JSON Array with FlatList

const students = [

    {
        id: 1,
        name: "Rahul"
    },

    {
        id: 2,
        name: "Amit"
    }

];

<FlatList
    data={students}
    keyExtractor={
        item =>
        item.id.toString()
    }
    renderItem={({ item }) => (

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

    )}
/>

FlatList is useful for displaying arrays of JSON objects.

20. JSON from a REST API

A REST API commonly returns JSON data after a request.

GET /api/students

Response:

{
    "students": [
        {
            "id": 1,
            "name": "Rahul"
        },
        {
            "id": 2,
            "name": "Amit"
        }
    ]
}

The React Native application can parse and display this information.

21. Sending JSON to an API

JSON is also commonly used when sending data to a backend.

const user = {

    name: "Rahul",
    email: "rahul@example.com"

};

const response =
    await fetch(url, {

        method: "POST",

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

        body:
            JSON.stringify(user)

    });

JSON.stringify() converts the JavaScript object into a JSON string for the request body.

22. JSON for Login Data

Login information can be sent to an authentication API in JSON format.

const loginData = {

    email: email,
    password: password

};

axios.post(
    "/api/login",
    loginData
);

The backend can process the submitted JSON data and return a response.

23. JSON for Course Data

An education application can receive course information as JSON.

{
    "courses": [

        {
            "id": 1,
            "name": "React Native",
            "duration": "6 Months"
        },

        {
            "id": 2,
            "name": "Python",
            "duration": "4 Months"
        }

    ]
}

The array can be displayed using FlatList.

24. JSON for Student Data

{
    "id": 101,
    "name": "Rahul",
    "mobile": "9876543210",
    "course": "React Native",
    "isActive": true
}

A React Native application can use this structure to display student information.

25. Handling Missing JSON Properties

An API response may sometimes not contain an expected property. JavaScript can use a fallback value when necessary.

const name =
    user.name || "Unknown";

console.log(name);

Optional chaining can also help when accessing nested data.

console.log(
    user.address?.city
);

26. Common JSON Mistakes

  • Using single quotes instead of double quotes in JSON strings.
  • Forgetting commas between properties.
  • Adding an unnecessary trailing comma.
  • Putting quotation marks around numbers when a number is intended.
  • Using JavaScript comments inside JSON.
  • Forgetting to parse a JSON string when necessary.
  • Trying to access a property from an incorrect JSON structure.
  • Not checking whether API data exists before displaying it.

27. Complete JSON API Example

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

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

import axios from "axios";

export default function StudentsScreen() {

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

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

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

    async function loadStudents() {

        try {

            setLoading(true);

            const response =
                await axios.get(
                    "https://example.com/api/students"
                );

            setStudents(
                response.data.students
            );

        } catch (error) {

            setError(
                "Unable to load students"
            );

        } finally {

            setLoading(false);

        }

    }

    useEffect(() => {

        loadStudents();

    }, []);

    if (loading) {

        return (
            <ActivityIndicator />
        );

    }

    if (error) {

        return (
            <Text>
                {error}
            </Text>
        );

    }

    return (

        <FlatList
            data={students}
            keyExtractor={
                item =>
                item.id.toString()
            }
            renderItem={({ item }) => (

                <View>

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

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

                </View>

            )}
        />

    );

}

This example demonstrates how JSON returned by an API can be read and displayed in a React Native application.

28. JSON Best Practices

  • Use clear and meaningful property names.
  • Keep API response structures consistent.
  • Validate important data before displaying it.
  • Handle missing properties safely.
  • Use JSON.parse() only when you have a JSON string that needs parsing.
  • Use JSON.stringify() when converting JavaScript data to JSON text.
  • Keep API response structures easy to understand.
  • Handle malformed or unexpected API responses.

29. Important JSON Concepts

Concept Purpose
Object Stores related key-value pairs
Array Stores multiple values
String Stores text
Number Stores numeric values
Boolean Stores true or false
null Represents an absent value
JSON.parse() Converts JSON text into a JavaScript value
JSON.stringify() Converts a JavaScript value into JSON text

30. Complete JSON Workflow

React Native App
        ↓
Create Request
        ↓
Send Request
        ↓
Backend API
        ↓
JSON Response
        ↓
Parse JSON
        ↓
Store Data in State
        ↓
Render UI
        ↓
Display Information

For Sending Data:

JavaScript Object
        ↓
JSON.stringify()
        ↓
JSON Request Body
        ↓
Backend API

JSON is one of the most important concepts for React Native developers because APIs commonly use JSON to exchange structured data. Understanding objects, arrays, parsing, stringifying and API responses prepares you for working with real backend services.

📌 Key Points

  • JSON stands for JavaScript Object Notation.
  • JSON is commonly used for exchanging API data.
  • JSON objects use key-value pairs.
  • JSON supports strings, numbers, booleans, arrays, objects and null.
  • JSON arrays can contain multiple objects.
  • JSON.parse() converts JSON text into a JavaScript value.
  • JSON.stringify() converts JavaScript data into JSON text.
  • Fetch can parse JSON using response.json().
  • Axios commonly provides parsed API data through response.data.
  • JSON is frequently used for GET and POST API communication.
  • FlatList is useful for displaying arrays of JSON objects.
  • Understanding JSON is essential for working with REST APIs.

🧠 Quick Quiz

Question: Which JavaScript method converts a JavaScript object into a JSON string?