Lesson 49 of 60 – React and JSON
82%

React and JSON

JSON (JavaScript Object Notation) is a common format used to store and exchange structured data. React applications frequently receive JSON data from APIs and use that data to display dynamic content.

Note: JSON is a data format. React does not require JSON, but JSON is commonly used when React applications communicate with backend APIs.

1. What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight format for representing structured data.

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

JSON is easy for applications to exchange and process.

2. Why is JSON Used?

JSON is commonly used when a frontend application communicates with a backend server.

  • Sending data to an API
  • Receiving data from an API
  • Storing structured information
  • Exchanging data between applications
  • Representing API responses

3. JSON Object

A JSON object contains key-value pairs.

{
    "id": 101,
    "name": "Amit",
    "course": "React"
}

Keys are written inside double quotation marks.

4. JSON Strings

String values in JSON are written inside double quotation marks.

{
    "name": "Rahul",
    "city": "Aurangabad"
}

The values "Rahul" and "Aurangabad" are strings.

5. JSON Numbers

JSON can contain numeric values.

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

Numbers do not need quotation marks.

6. JSON Boolean Values

JSON supports the Boolean values true and false.

{
    "active": true,
    "verified": false
}

7. JSON null

JSON supports the value null to represent the absence of a value.

{
    "middleName": null
}

8. JSON Arrays

A JSON array contains multiple values inside square brackets.

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

Arrays are useful for representing lists of data.

9. Array of JSON Objects

An API can return an array containing multiple objects.

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

This structure is common in APIs that return lists of records.

10. Accessing JSON Data in JavaScript

After JSON data has been converted into JavaScript data, object properties can be accessed using dot notation.

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

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

11. JSON and JavaScript Objects

JSON and JavaScript objects can look similar, but they are not exactly the same thing.

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

This is a JavaScript object. JSON is a text-based data format.

12. JSON.parse()

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

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

const student = JSON.parse(jsonData);

console.log(student.name);

13. JSON.stringify()

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

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

const jsonData =
    JSON.stringify(student);

console.log(jsonData);

14. JSON.parse() vs JSON.stringify()

JSON string
     ↓
JSON.parse()
     ↓
JavaScript value

JavaScript value
     ↓
JSON.stringify()
     ↓
JSON string

Use parse() to convert JSON text into JavaScript data and stringify() to convert JavaScript data into JSON text.

15. JSON from fetch()

When using fetch(), the response can be converted to JSON using the json() method.

fetch("/api/students")
    .then(response => response.json())
    .then(data => {
        console.log(data);
    });

The parsed data can then be used by the React component.

16. JSON with Axios

Axios commonly provides parsed response data through response.data.

axios.get("/api/students")
    .then(response => {

        console.log(
            response.data
        );

    });

17. Display JSON Data in React

JSON data received from an API can be stored in state and displayed in JSX.

const [student, setStudent] = useState(null);

useEffect(() => {

    fetch("/api/student")
        .then(response => response.json())
        .then(data => {
            setStudent(data);
        });

}, []);

18. Display JSON Object Properties

{student && (
    <div>

        <h2>
            {student.name}
        </h2>

        <p>
            Course: {student.course}
        </p>

        <p>
            Age: {student.age}
        </p>

    </div>
)}

19. Display JSON Arrays with map()

When JSON contains an array, the map() method can be used to render each item.

{students.map(student => (
    <p key={student.id}>
        {student.name}
    </p>
))}

20. Nested JSON Objects

JSON objects can contain other objects.

{
    "name": "Rahul",
    "address": {
        "city": "Aurangabad",
        "state": "Bihar"
    }
}

The nested value can be accessed like this:

student.address.city

21. Nested JSON Arrays

JSON can also contain arrays inside objects.

{
    "name": "Rahul",
    "skills": [
        "HTML",
        "CSS",
        "React"
    ]
}

React can render the skills using map().

{student.skills.map(skill => (
    <li key={skill}>
        {skill}
    </li>
))}

22. Sending JSON to an API

React applications can send JavaScript objects to APIs. The HTTP client typically serializes the request body as JSON.

fetch("/api/students", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        name: "Rahul",
        course: "React"
    })
});

23. JSON with Form Data

Form data can be stored in a JavaScript object and then sent as JSON.

const formData = {
    name: "Amit",
    email: "amit@example.com",
    course: "React"
};

fetch("/api/students", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify(formData)
});

24. JSON and Loading States

JSON data usually arrives asynchronously. Therefore, the component should consider the state before the data is available.

if (loading) {
    return <p>Loading...</p>;
}

if (error) {
    return <p>Error: {error}</p>;
}

return (
    <StudentList
        students={students}
    />
);

25. JSON Data Validation

Applications should not blindly assume that external data always contains every expected property.

{student?.name}

Optional chaining can safely access a property when the object may not yet exist.

26. Common JSON Mistakes

  • Using single quotes in standard JSON strings.
  • Forgetting quotation marks around JSON keys.
  • Adding a trailing comma where JSON does not allow it.
  • Confusing JSON strings with JavaScript objects.
  • Forgetting to parse JSON text when necessary.
  • Assuming an API always returns the expected structure.
  • Trying to map over an object instead of an array.
  • Trying to access data before it has been loaded.

27. JSON API Workflow

React Component
       ↓
API Request
       ↓
Server
       ↓
JSON Response
       ↓
Parse / Response Data
       ↓
React State
       ↓
JSX
       ↓
User Interface

28. Complete JSON Fetch Example

import {
    useEffect,
    useState
} from "react";

function Students() {

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

    useEffect(() => {

        fetch("/api/students")
            .then(response => {

                if (!response.ok) {
                    throw new Error(
                        "Failed to fetch students"
                    );
                }

                return response.json();
            })
            .then(data => {

                setStudents(data);

            })
            .catch(error => {

                console.log(error);

            });

    }, []);

    return (
        <div>

            <h2>
                Students
            </h2>

            {students.map(student => (

                <div
                    key={student.id}
                    className="card mt-3"
                >

                    <div className="card-body">

                        <h4>
                            {student.name}
                        </h4>

                        <p>
                            Course:
                            {student.course}
                        </p>

                    </div>

                </div>

            ))}

        </div>
    );
}

export default Students;

29. Complete JSON Form Example

import {
    useState
} from "react";

function StudentForm() {

    const [name, setName] = useState("");
    const [course, setCourse] = useState("");

    async function handleSubmit(e) {

        e.preventDefault();

        const student = {
            name: name,
            course: course
        };

        const response = await fetch(
            "/api/students",
            {
                method: "POST",

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

                body:
                    JSON.stringify(student)
            }
        );

        const data = await response.json();

        console.log(data);
    }

    return (
        <form onSubmit={handleSubmit}>

            <input
                value={name}
                onChange={e =>
                    setName(e.target.value)
                }
                placeholder="Student Name"
            />

            <input
                value={course}
                onChange={e =>
                    setCourse(e.target.value)
                }
                placeholder="Course"
            />

            <button type="submit">
                Save
            </button>

        </form>
    );
}

export default StudentForm;

30. JSON Best Practices in React

  • Understand the structure of the JSON returned by your API.
  • Use response.json() when working with JSON responses from fetch.
  • Use response.data when reading Axios response data.
  • Use JSON.stringify() when sending JSON text where required.
  • Use JSON.parse() when converting JSON text into JavaScript data.
  • Handle loading and error states.
  • Check that expected properties exist before displaying them.
  • Use stable keys when rendering JSON arrays.
  • Keep API data handling separate and organized.
  • Do not assume external JSON data is always complete or valid.
JSON
 ↓
JavaScript Data
 ↓
React State
 ↓
JSX
 ↓
UI

📌 Key Points

  • JSON stands for JavaScript Object Notation.
  • JSON is commonly used for exchanging data between applications.
  • JSON can contain strings, numbers, booleans, arrays, objects, and null.
  • JSON.parse() converts JSON text into a JavaScript value.
  • JSON.stringify() converts a JavaScript value into JSON text.
  • fetch() can convert an API response using response.json().
  • Axios commonly provides parsed response data through response.data.
  • JSON arrays can be rendered in React using map().
  • JSON objects can contain nested objects and arrays.
  • React applications commonly use JSON when communicating with APIs.

🧠 Quick Quiz

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