Working with JSON in JavaScript: A Complete Guide
Published on January 25, 2026
JSON and JavaScript go hand in hand. In this comprehensive guide, we'll explore how to work with JSON data in JavaScript, from basic parsing to advanced manipulation techniques.
Parsing JSON with JSON.parse()
The JSON.parse() method converts a JSON string into a JavaScript object.
const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "John"
console.log(obj.age); // 30Converting to JSON with JSON.stringify()
The JSON.stringify() method converts a JavaScript object into a JSON string.
const obj = { name: "John", age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // '{"name":"John","age":30}'Pretty Printing JSON
Use the third parameter of JSON.stringify() to add indentation for readable output.
const obj = { name: "John", age: 30 };
const prettyJson = JSON.stringify(obj, null, 2);
console.log(prettyJson);
// {
// "name": "John",
// "age": 30
// }Handling Parse Errors
Always wrap JSON.parse() in a try-catch block to handle invalid JSON gracefully.
function safeJsonParse(jsonString) {
try {
return JSON.parse(jsonString);
} catch (error) {
console.error('Invalid JSON:', error.message);
return null;
}
}Using the Replacer Function
The second parameter of JSON.stringify() can be a replacer function to transform values during serialization.
const obj = { name: "John", password: "secret123" };
const safeJson = JSON.stringify(obj, (key, value) => {
if (key === 'password') return undefined; // Exclude
return value;
});
console.log(safeJson); // '{"name":"John"}'Using the Reviver Function
The second parameter of JSON.parse() can be a reviver function to transform values during parsing.
const jsonString = '{"date": "2026-01-25T10:00:00Z"}';
const obj = JSON.parse(jsonString, (key, value) => {
if (key === 'date') return new Date(value);
return value;
});
console.log(obj.date instanceof Date); // trueDeep Cloning Objects with JSON
A quick way to deep clone an object (with limitations) is using JSON methods.
const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));
clone.b.c = 999;
console.log(original.b.c); // 2 (unchanged)Fetching JSON from an API
Modern JavaScript makes it easy to fetch and parse JSON from APIs.
async function fetchUserData() {
const response = await fetch('/api/user');
const data = await response.json();
return data;
}Best Practices
- Always validate JSON before parsing in production code
- Use try-catch blocks when parsing user-provided JSON
- Be aware that JSON.stringify() ignores functions and undefined values
- Consider using a schema validator for complex JSON structures
- Use pretty printing only for debugging, not for data storage
Try Our JSON Formatter
Format, validate, and minify your JSON data instantly - no sign-up required!
Open JSON Formatter