Native JSON in JavaScript
JavaScript provides the global JSON object with two primary methods for handling JSON data, available in all browsers and Node.js environments without any import.
Core Methods:
JSON.parse(text)— Converts a JSON string to a JavaScript value.JSON.stringify(value, replacer, space)— Converts a JavaScript value to a JSON string.
Pretty Printing in JavaScript
Pass null as the replacer and 2 as the space parameter to produce indented output.
Safe Parsing Pattern
Always wrap JSON.parse() in a try/catch block to prevent unhandled SyntaxError exceptions from crashing your application.
// Parse JSON string to object
const json = '{"name":"Alice","score":99,"active":true}';
const obj = JSON.parse(json);
console.log(obj.name); // Alice
// Stringify with pretty formatting (2-space indent)
const pretty = JSON.stringify(obj, null, 2);
console.log(pretty);
// {
// "name": "Alice",
// "score": 99,
// "active": true
// }
// Safe JSON parsing (prevents SyntaxError crashes)
function safeParseJSON(text) {
try {
return { data: JSON.parse(text), error: null };
} catch (e) {
return { data: null, error: e.message };
}
}
// Fetch and parse API response in Node.js / Browser
async function fetchJSON(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json(); // automatically calls JSON.parse
}