jsondecode.com logo

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); // object

Serialize 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 unchanged

Frequently Asked Questions

How do I parse JSON in JavaScript?

Use JSON.parse(jsonString). It throws a SyntaxError if the string is not valid JSON, so wrap in try/catch for untrusted input.

How do I convert a JavaScript object to JSON?

Use JSON.stringify(obj). Pass null, 2 as extra arguments for a pretty-printed result with 2-space indentation.

Why does JSON.stringify() return undefined for some values?

JSON.stringify() omits properties with undefined, function, or Symbol values. It also converts NaN and Infinity to null.

How do I fetch JSON from an API in JavaScript?

Use fetch(url).then(res => res.json()). The .json() method parses the response body as JSON and returns a Promise.

What is the JSON reviver function?

The second argument to JSON.parse() is a reviver function called on each key/value pair. Use it to transform values, e.g., converting date strings to Date objects.

Format and validate your JSON instantly

Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.

Open JSON Formatter →

If jsondecode.com saved you time, share it with your team

Free forever. No ads. No sign-up. Help other developers find it.