Languages Knowledge Base

Working with JSON in JavaScript and Node.js

Complete guide to JSON in JavaScript: JSON.parse(), JSON.stringify(), pretty printing, safe parsing patterns, and handling large JSON payloads in Node.js.

In JavaScript, use JSON.parse(text) to convert a JSON string to an object and JSON.stringify(obj, null, 2) to serialize it back with 2-space indentation. Both methods are built into all modern JavaScript environments.

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.

json
// 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
}

Try the free JSON Formatter

Runs entirely in your browser — no upload, no signup, and your data never leaves your device.

Open JSON Formatter

Frequently Asked Questions

How do I pretty print JSON in JavaScript?

Use JSON.stringify(obj, null, 2) where 2 is the number of spaces. Replace 2 with 4 for 4-space indentation.

What is the difference between JSON.parse and JSON.stringify?

JSON.parse converts a JSON text string into a JavaScript object. JSON.stringify converts a JavaScript object into a JSON string.

How do I handle JSON parse errors in JavaScript?

Wrap JSON.parse() in a try/catch block. On failure, a SyntaxError is thrown with the error message.

Is there a file size limit for JSON.parse in the browser?

Browser memory limits apply. For files larger than 5MB, use Web Workers to parse off the main thread.

Related JSON Topics & Reference Articles