How to Parse and Manipulate JSON in JavaScript [with Code Examples]
If you're a web developer, working with JSON is not just a skill—it's a daily necessity. From fetching data from a server to sending information back, JSON is the universal language of modern web APIs.
This practical guide will teach you everything you need to know about handling JSON in JavaScript. We'll cover the two most essential methods, JSON.parse()
and JSON.stringify()
, and show you how to use them in real-world scenarios like working with an API.
New to JSON? Before you dive in, make sure you understand the basics by reading our Ultimate Guide to JSON: Syntax, Best Practices & Common Errors.
The Core of JSON in JavaScript
JavaScript provides a built-in global JSON
object that has two primary methods for working with JSON data:
JSON.parse()
: Converts a JSON data string into a JavaScript object. (Think: Reading or Receiving data).JSON.stringify()
: Converts a JavaScript object into a JSON data string. (Think: Creating or Sending data).
Let's break down each one with examples.
Parsing JSON: From String to JavaScript Object with JSON.parse()
Imagine you've received data from an API. It will almost always arrive as a string, even if it's formatted like an object. To use this data in JavaScript, you first need to "parse" it into a real JavaScript object.
Here’s a typical JSON string you might get from a server:
{
"id": 101,
"username": "dev_guru",
"is_active": true,
"roles": ["editor", "admin"],
"profile": {
"name": "Alex Doe",
"email": "alex.doe@example.com"
}
}
Now, let's convert this string into a usable object:
// Parse the JSON string into a JavaScript object
const userObject = JSON.parse(userJSON);
// Now you can access its properties using dot notation
console.log(userObject.username); // Output: "dev_guru"
console.log(userObject.roles[0]); // Output: "editor"
console.log(userObject.profile.email); // Output: "alex.doe@example.com"
It's that simple! JSON.parse()
takes the text and gives you back a native JavaScript object you can interact with.
Handling Parsing Errors
What happens if the JSON string is invalid? JSON.parse()
will throw a SyntaxError
. You should always wrap your parsing logic in a try...catch
block to handle potential errors gracefully.
const badJSON = '{"username": "test",}'; // Invalid JSON due to trailing comma
try {
const user = JSON.parse(badJSON);
console.log(user);
} catch (error) {
console.error("Failed to parse JSON:", error);
// Output: Failed to parse JSON: SyntaxError: ...
}
Struggling with errors? Learn how to find and fix common issues in our guide to Mastering JSON Validation: Tools, Techniques & Tips.
Creating JSON: From JavaScript Object to String with JSON.stringify()
Now, let's do the reverse. Imagine you have a JavaScript object that you need to send to a server (e.g., submitting a form or saving user settings). You must first convert this object into a valid JSON string.
Here's our JavaScript object:
const userSettings = {
theme: "dark",
notifications: {
email: true,
push: false,
},
lastLogin: new Date(), // Note this Date object
};
Let's stringify it:
const settingsJSON = JSON.stringify(userSettings);
console.log(settingsJSON);
// Output: {"theme":"dark","notifications":{"email":true,"push":false},"lastLogin":"2023-10-27T10:00:00.000Z"}
Notice a few things:
- The output is a single line of text with no extra spaces.
- The
Date
object was automatically converted into a standard ISO 8601 date string. - Property names are wrapped in double quotes, as required by the JSON standard.
Making JSON Readable with space
The one-line output is efficient but hard to read. JSON.stringify()
has an optional third argument, space
, that lets you "pretty-print" the output. You can use a number (for spaces) or a string (like a tab \t
).
// Using 2 spaces for indentation
const readableJSON = JSON.stringify(userSettings, null, 2);
console.log(readableJSON);
Output:
{
"theme": "dark",
"notifications": {
"email": true,
"push": false
},
"lastLogin": "2023-10-27T10:00:00.000Z"
}
This is much easier for humans to read and debug!
Real-World Use Case: Fetching API Data
The most common scenario for these methods is fetching data from an API using the fetch
function. The fetch
API has a built-in .json()
method that is a handy shortcut: it reads the response stream and runs JSON.parse()
on it for you.
Here's how to fetch user data from a placeholder API:
const apiUrl = "https://formatjsononline.com/api/users/usr_1";
fetch(apiUrl)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((user) => {
console.log(`Fetched user: ${user.name} (${user.email})`);
})
.catch((error) => {
console.error("There was a problem with the fetch operation:", error);
});