DEV Community

swetha palani
swetha palani

Posted on

JSON in react

What is JSON?

  • JSON stands for JavaScript Object Notation.
  • It is a lightweight data format used for storing and exchanging data.
  • It looks like JavaScript objects, but it’s just text (a string).

Why JSON is used?

  • Easy to read and write (human-friendly).
  • Easy for machines to parse and generate.
  • Commonly used in APIs to send data between a server and a client (like React, mobile apps, etc.).

Example of JSON

{
  "name": "Swetha",
  "age": 22,
  "isStudent": true,
  "skills": ["JavaScript", "React", "Python"]
}
Enter fullscreen mode Exit fullscreen mode

This is just data in key-value pairs.

JSON Rules

  1. Data is in key-value pairs"key": "value"
  2. Keys must be in double quotes"name", not name.
  3. Values can be:
  • String → "Swetha"
  • Number → 22
  • Boolean → true / false
  • Null → null
  • Array → [1,2,3]
  • Object → { "city": "Chennai" }

🔹 JSON vs JavaScript Object

  • JSON:
  { "name": "Swetha", "age": 22 }
Enter fullscreen mode Exit fullscreen mode
  • JS Object:
  { name: "Swetha", age: 22 }
Enter fullscreen mode Exit fullscreen mode

Difference: In JSON, keys must be in double quotes, and it’s only text, not an actual object.

In simple words:
JSON is a text-based format to store and share data between different systems, especially in web development.

How JSON is used in React

  1. A backend/server sends data in JSON format.
  2. React fetches it using fetch() or axios.
  3. JSON is converted into a JavaScript object using .json().
  4. React renders that data inside components.

Step-by-step

  1. fetch() → calls API.
  2. .json() → parses JSON string into JS object.
  3. setUsers(data) → saves data into state.
  4. map() → displays the data dynamically.

Interview 1-Minute Answer

“JSON is mainly used in React when fetching data from APIs. The server usually returns a JSON response, which we parse using .json(). Then we store it in state and render it inside components using methods like .map().”

Top comments (0)