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.
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.
JSON is commonly used when a frontend application communicates with a backend server.
A JSON object contains key-value pairs.
{
"id": 101,
"name": "Amit",
"course": "React"
}
Keys are written inside double quotation marks.
String values in JSON are written inside double quotation marks.
{
"name": "Rahul",
"city": "Aurangabad"
}
The values "Rahul" and "Aurangabad" are strings.
JSON can contain numeric values.
{
"age": 22,
"fee": 15000
}
Numbers do not need quotation marks.
JSON supports the Boolean values true and false.
{
"active": true,
"verified": false
}
JSON supports the value null to represent the absence of a
value.
{
"middleName": null
}
A JSON array contains multiple values inside square brackets.
{
"courses": [
"HTML",
"CSS",
"React"
]
}
Arrays are useful for representing lists of data.
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.
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);
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.
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);
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);
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.
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.
Axios commonly provides parsed response data through
response.data.
axios.get("/api/students")
.then(response => {
console.log(
response.data
);
});
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);
});
}, []);
{student && (
<div>
<h2>
{student.name}
</h2>
<p>
Course: {student.course}
</p>
<p>
Age: {student.age}
</p>
</div>
)}
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>
))}
JSON objects can contain other objects.
{
"name": "Rahul",
"address": {
"city": "Aurangabad",
"state": "Bihar"
}
}
The nested value can be accessed like this:
student.address.city
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>
))}
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"
})
});
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)
});
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}
/>
);
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.
React Component
↓
API Request
↓
Server
↓
JSON Response
↓
Parse / Response Data
↓
React State
↓
JSX
↓
User Interface
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;
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;
response.json() when working with JSON responses from fetch.response.data when reading Axios response data.JSON.stringify() when sending JSON text where required.JSON.parse() when converting JSON text into JavaScript data.JSON
↓
JavaScript Data
↓
React State
↓
JSX
↓
UI
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().response.data.map().Question: Which method converts a JSON string into a JavaScript value?