JSON in JavaScript — Parse, Stringify & Fetch
JavaScript has native JSON support through the global JSON object. JSON was designed with JavaScript in mind, so the integration is seamless.
Parse a JSON string
Use JSON.parse() to convert a JSON string into a JavaScript object or array.
const jsonString = '{"name":"Alice","age":30,"active":true}';
const data = JSON.parse(jsonString);
console.log(data.name); // Alice
console.log(data.age); // 30
console.log(typeof data); // objectSerialize to JSON
Use JSON.stringify() to convert a JavaScript value to a JSON string. Pass null, 2 as the second and third arguments for pretty-printing.
const data = { name: "Alice", scores: [95, 87], active: true };
// Compact
const compact = JSON.stringify(data);
// {"name":"Alice","scores":[95,87],"active":true}
// Pretty-printed
const pretty = JSON.stringify(data, null, 2);
console.log(pretty);Fetch JSON from an API
The Fetch API returns a Response object. Call .json() to parse the body as JSON.
const response = await fetch("https://api.example.com/users/1");
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const user = await response.json();
console.log(user.name);Handle parse errors
JSON.parse() throws a SyntaxError on invalid JSON. Always wrap in try/catch when handling untrusted input.
try {
const data = JSON.parse('{"name": "Alice", invalid}');
} catch (err) {
if (err instanceof SyntaxError) {
console.error("Invalid JSON:", err.message);
}
}Deep clone with JSON
A common pattern to deep-clone a plain object (no functions, no undefined, no circular refs).
const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));
clone.b.c = 99;
console.log(original.b.c); // 2 — original unchangedRelated Tools
JSON in Other Languages
Format and validate your JSON instantly
Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.
Open JSON Formatter →