Handling JSON Data in JavaScript
fetch-json-api.png: "Illustration of JavaScript fetch() retrieving JSON from API
JSON (JavaScript Object Notation) is the most common data format used to exchange information between a client and server. JavaScript provides built-in methods to easily parse, stringify, and manipulate JSON data.
This guide walks you through how to handle JSON in JavaScript, especially when working with APIs.
JSON is a lightweight data-interchange format. It is text-based and easy to read/write.
{
"name": "John",
"age": 30,
"skills": ["JavaScript", "React"]
}
Use JSON.parse()
to convert a JSON string into a JavaScript object.
const jsonString = '{"name":"Alice","age":25}';
const user = JSON.parse(jsonString);
console.log(user.name); // Alice
⚠️ Make sure the string is valid JSON or parsing will throw an error.
Use JSON.stringify()
to convert a JavaScript object into a JSON string.
const user = {
name: "Bob",
age: 28
};
const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"Bob","age":28}'
You can also format the output for readability:
console.log(JSON.stringify(user, null, 2));
Most APIs return JSON. Use fetch()
and response.json()
to retrieve and parse data:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching JSON:', error));
const broken = '{name: "Test"}';
const parsed = JSON.parse(broken); // ❌ Throws SyntaxError
Always use try...catch
to handle JSON parsing:
try {
const parsed = JSON.parse(broken);
} catch (e) {
console.error("Invalid JSON:", e);
}
Use Cases for JSON in JavaScript
Reading and writing configuration
Communicating with REST APIs
Saving user data to localStorage
Exchanging data between frontend and backend
JSON is essential to modern web development. JavaScript's built-in JSON.parse()
and JSON.stringify()
make it simple to convert between JSON strings and JavaScript objects. Mastering these methods helps you integrate APIs, store data, and build efficient front-end and back-end systems.