JSON in JavaScript – Complete Guide
JavaScript has native, built-in support for JSON through two global methods: JSON.parse() and JSON.stringify(). This guide covers everything you need to know about working with JSON in JavaScript — from basic parsing to advanced techniques like deep cloning, custom serialization, and fetching JSON from APIs.
JSON.parse() — Converting JSON String to Object
JSON.parse() takes a JSON string and converts it into a JavaScript object, array, or primitive value.
const jsonString = '{"name": "Alice", "age": 28, "active": true}';
const user = JSON.parse(jsonString);
console.log(user.name); // "Alice"
console.log(user.age); // 28
Handling Parse Errors
Always wrap JSON.parse() in a try-catch block — invalid JSON will throw a SyntaxError.
try {
const data = JSON.parse(invalidString);
} catch (error) {
console.error('Invalid JSON:', error.message);
}
JSON.stringify() — Converting Object to JSON String
JSON.stringify() converts a JavaScript object or array into a JSON string. It accepts optional parameters for filtering and formatting.
const user = { name: "Alice", age: 28, active: true };
const jsonString = JSON.stringify(user);
// '{"name":"Alice","age":28,"active":true}'
// Pretty-printed with 2-space indentation
const pretty = JSON.stringify(user, null, 2);
/*
{
"name": "Alice",
"age": 28,
"active": true
}
*/
Filtering with a Replacer
// Only include specific keys
const filtered = JSON.stringify(user, ['name', 'age']);
// '{"name":"Alice","age":28}'
What JSON.stringify() Cannot Serialize
undefinedvalues — omitted from objects, converted tonullin arraysFunctionvalues — omitted silentlySymbolkeys and values — omitted silentlyInfinityandNaN— converted tonull- Circular references — throws a
TypeError Dateobjects — converted to ISO string format
Fetching JSON from an API
The Fetch API makes it easy to retrieve JSON data from REST APIs.
// Basic fetch with JSON
async function getUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) throw new Error('HTTP error: ' + response.status);
const data = await response.json(); // Parses JSON automatically
return data;
}
// Sending JSON in a POST request
async function createUser(userData) {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData)
});
return response.json();
}
Deep Cloning Objects with JSON
A common trick to deep clone a plain JavaScript object is to stringify and then parse it. This creates a completely independent copy with no shared references.
const original = { user: { name: "Alice", scores: [1, 2, 3] } };
const clone = JSON.parse(JSON.stringify(original));
clone.user.name = "Bob";
console.log(original.user.name); // "Alice" — not affected
Limitation: This method does not work for objects containing functions, undefined, Date objects, or circular references. Use structuredClone() for a more robust deep clone in modern browsers.
JSON with localStorage
localStorage only stores strings, so you must serialize objects with JSON.stringify() before storing and parse them with JSON.parse() when reading.
// Save to localStorage
localStorage.setItem('user', JSON.stringify({ name: 'Alice', age: 28 }));
// Read from localStorage
const user = JSON.parse(localStorage.getItem('user'));
console.log(user.name); // "Alice"
JSON Best Practices in JavaScript
- Always use try-catch when parsing JSON from external sources
- Validate the structure of parsed JSON before accessing properties
- Use
JSON.stringify(data, null, 2)for readable debug output - Set
Content-Type: application/jsonheader when sending JSON in fetch requests - Use
response.json()instead of manually parsing the response text - Avoid storing sensitive data in JSON that gets logged or transmitted insecurely
Paste your JSON into JSONHack to format, validate, and debug it in seconds.