JSON is native to JavaScript โ the format was literally derived from JavaScript object syntax. Despite that, there are important rules, patterns, and best practices to understand when parsing and serializing JSON in JavaScript and Node.js. This comprehensive guide covers everything from basics to advanced topics like TypeScript integration, streaming, and performance optimization.
JSON.parse() โ Converting Strings to Objects
JSON.parse() converts a JSON string into a JavaScript value (object, array, string, number, boolean, or null). It's the primary method for deserializing JSON data.
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"
// Parsing arrays
const arrayJson = '[1, 2, 3, "four", true]';
const arr = JSON.parse(arrayJson);
console.log(arr[3]); // "four"
// Parsing primitive values
JSON.parse('"hello"'); // "hello" (string)
JSON.parse('42'); // 42 (number)
JSON.parse('true'); // true (boolean)
JSON.parse('null'); // null
JSON.stringify() โ Converting Objects to Strings
JSON.stringify() converts a JavaScript value into a JSON string. It accepts three arguments: the value, an optional replacer, and an optional space value for formatting.
const user = { name: "Bob", age: 25, active: true };
// Compact output (default)
console.log(JSON.stringify(user));
// {"name":"Bob","age":25,"active":true}
// Pretty-printed with 2-space indentation
console.log(JSON.stringify(user, null, 2));
// {
// "name": "Bob",
// "age": 25,
// "active": true
// }
// Using tab indentation
console.log(JSON.stringify(user, null, '\t'));
// Using a replacer array to include only specific keys
console.log(JSON.stringify(user, ['name', 'age']));
// {"name":"Bob","age":25}
What Gets Dropped or Transformed by JSON.stringify()
Some JavaScript values cannot be represented in JSON and are silently omitted or transformed. Understanding this is critical to avoid data loss:
const obj = {
name: "Alice",
fn: () => "hello", // functions โ dropped
undef: undefined, // undefined โ dropped
sym: Symbol("x"), // symbols โ dropped
date: new Date(), // Date โ converted to ISO string
nan: NaN, // NaN โ becomes null
inf: Infinity, // Infinity โ becomes null
negInf: -Infinity, // -Infinity โ becomes null
bigInt: 123n, // BigInt โ throws TypeError!
regex: /pattern/gi, // RegExp โ becomes {}
map: new Map([['a', 1]]), // Map โ becomes {}
set: new Set([1, 2, 3]) // Set โ becomes {}
};
console.log(JSON.stringify(obj, null, 2));
// {
// "name": "Alice",
// "date": "2025-07-15T10:30:00.000Z",
// "nan": null,
// "inf": null,
// "negInf": null,
// "regex": {},
// "map": {},
// "set": {}
// }
Important: BigInt values throw a TypeError. You must handle them explicitly with a replacer function or convert them to strings before stringifying.
Comprehensive Error Handling Patterns
JSON.parse() throws a SyntaxError if the input is invalid. Robust error handling is essential when processing external data.
Basic Try-Catch Pattern
function safeParseJSON(str) {
try {
return { data: JSON.parse(str), error: null };
} catch (err) {
return { data: null, error: err.message };
}
}
const { data, error } = safeParseJSON('{"broken": }');
if (error) {
console.error("Failed to parse JSON:", error);
// "Failed to parse JSON: Unexpected token } in JSON at position 11"
}
Generic Safe Parser with Default Value
function parseJSONWithDefault(str, defaultValue = null) {
try {
return JSON.parse(str);
} catch {
return defaultValue;
}
}
// Returns parsed object or default
const config = parseJSONWithDefault(userInput, { theme: 'light' });
Typed Error Handling with Custom Errors
class JSONParseError extends Error {
constructor(message, originalError, input) {
super(message);
this.name = 'JSONParseError';
this.originalError = originalError;
this.input = input.substring(0, 100); // Truncate for logging
}
}
function parseJSONStrict(str) {
if (typeof str !== 'string') {
throw new JSONParseError('Input must be a string', null, String(str));
}
try {
return JSON.parse(str);
} catch (err) {
throw new JSONParseError(
`Invalid JSON: ${err.message}`,
err,
str
);
}
}
Async Error Handling Pattern
async function fetchAndParseJSON(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const text = await response.text();
try {
return JSON.parse(text);
} catch (err) {
throw new Error(`Invalid JSON from ${url}: ${err.message}`);
}
}
// Usage with error handling
try {
const data = await fetchAndParseJSON('/api/users');
} catch (err) {
if (err.message.includes('Invalid JSON')) {
console.error('Server returned malformed data');
} else {
console.error('Network or server error:', err.message);
}
}
Fetching JSON with fetch() and axios
The most common real-world usage is fetching JSON from APIs. Here are patterns for both fetch and axios.
Using fetch() โ Browser and Node.js 18+
// Basic GET request
async function getUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json(); // Automatically parses JSON
}
// POST request with JSON body
async function createUser(userData) {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
body: JSON.stringify(userData)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Request failed');
}
return response.json();
}
// With timeout using AbortController
async function fetchWithTimeout(url, timeout = 5000) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { signal: controller.signal });
return response.json();
} finally {
clearTimeout(timeoutId);
}
}
Using axios
import axios from 'axios';
// axios automatically parses JSON responses
const response = await axios.get('https://api.example.com/users/1');
console.log(response.data); // Already parsed object
// POST with automatic JSON serialization
const newUser = await axios.post('https://api.example.com/users', {
name: 'Alice',
email: 'alice@example.com'
});
// With interceptors for global error handling
axios.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
// Handle authentication error
window.location.href = '/login';
}
return Promise.reject(error);
}
);
Using the Reviver Function
The second argument to JSON.parse() is a reviver โ a function called for each key/value pair that lets you transform values during parsing. This is powerful for type conversion.
// Converting date strings to Date objects
const json = '{"name": "Alice", "createdAt": "2025-01-15T10:00:00Z"}';
const data = JSON.parse(json, (key, value) => {
// Check if value looks like an ISO date string
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
return new Date(value);
}
return value;
});
console.log(data.createdAt instanceof Date); // true
console.log(data.createdAt.getFullYear()); // 2025
// More complex reviver with multiple transformations
function createReviver(dateFields, numberFields) {
return (key, value) => {
if (dateFields.includes(key) && typeof value === 'string') {
return new Date(value);
}
if (numberFields.includes(key) && typeof value === 'string') {
return parseFloat(value);
}
return value;
};
}
const jsonData = '{"id": "123", "price": "19.99", "createdAt": "2025-01-15"}';
const reviver = createReviver(['createdAt'], ['id', 'price']);
const product = JSON.parse(jsonData, reviver);
console.log(typeof product.id); // "number"
console.log(typeof product.price); // "number"
console.log(product.createdAt); // Date object
Using the Replacer Function
The replacer in JSON.stringify() lets you filter or transform values during serialization.
const user = {
id: 1,
name: "Alice",
password: "secret123",
email: "alice@example.com",
createdAt: new Date(),
balance: 123n // BigInt
};
// Filter out sensitive fields and handle special types
function secureReplacer(key, value) {
// Remove sensitive fields
if (key === 'password') return undefined;
// Convert BigInt to string
if (typeof value === 'bigint') return value.toString();
// Convert Date to timestamp
if (value instanceof Date) return value.toISOString();
return value;
}
console.log(JSON.stringify(user, secureReplacer, 2));
// {
// "id": 1,
// "name": "Alice",
// "email": "alice@example.com",
// "createdAt": "2025-07-15T10:30:00.000Z",
// "balance": "123"
// }
TypeScript JSON Handling
TypeScript adds type safety to JSON operations, but requires careful handling since JSON.parse() returns any by default.
Defining Interfaces for JSON Data
interface User {
id: number;
name: string;
email: string;
createdAt: string; // Dates come as strings in JSON
roles: string[];
}
interface ApiResponse<T> {
data: T;
status: 'success' | 'error';
message?: string;
}
// Type assertion (simple but unsafe)
const user = JSON.parse(jsonString) as User;
// Better: generic parse function with type parameter
function parseJSON<T>(json: string): T {
return JSON.parse(json);
}
const user = parseJSON<User>(jsonString);
Type Guards for Runtime Validation
interface User {
id: number;
name: string;
email: string;
}
// Type guard function
function isUser(obj: unknown): obj is User {
return (
typeof obj === 'object' &&
obj !== null &&
typeof (obj as User).id === 'number' &&
typeof (obj as User).name === 'string' &&
typeof (obj as User).email === 'string'
);
}
// Safe parse with validation
function parseUser(json: string): User | null {
try {
const parsed = JSON.parse(json);
if (isUser(parsed)) {
return parsed;
}
console.error('Invalid user data structure');
return null;
} catch {
console.error('Invalid JSON');
return null;
}
}
const user = parseUser(jsonString);
if (user) {
// TypeScript knows user is User here
console.log(user.name);
}
Using Zod for Schema Validation
import { z } from 'zod';
// Define schema
const UserSchema = z.object({
id: z.number(),
name: z.string().min(1),
email: z.string().email(),
createdAt: z.string().datetime(),
roles: z.array(z.string())
});
type User = z.infer<typeof UserSchema>;
// Parse and validate in one step
function parseAndValidateUser(json: string): User {
const parsed = JSON.parse(json);
return UserSchema.parse(parsed); // Throws if invalid
}
// Safe version that returns result object
function safeParseUser(json: string) {
try {
const parsed = JSON.parse(json);
return UserSchema.safeParse(parsed);
} catch {
return { success: false, error: new Error('Invalid JSON') };
}
}
JSON Streaming for Large Data
Standard JSON.parse() loads the entire string into memory before parsing. For large datasets, streaming parsers process data incrementally.
NDJSON (Newline Delimited JSON)
NDJSON is a format where each line is a separate JSON object, making it ideal for streaming:
// NDJSON format (each line is valid JSON)
// {"id": 1, "name": "Alice"}
// {"id": 2, "name": "Bob"}
// {"id": 3, "name": "Charlie"}
// Processing NDJSON stream
async function processNDJSON(url) {
const response = await fetch(url);
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop(); // Keep incomplete line in buffer
for (const line of lines) {
if (line.trim()) {
const obj = JSON.parse(line);
console.log('Received:', obj);
}
}
}
}
Using stream-json for Node.js
import { parser } from 'stream-json';
import { pick } from 'stream-json/filters/Pick';
import { streamArray } from 'stream-json/streamers/StreamArray';
import { createReadStream } from 'fs';
import { pipeline } from 'stream/promises';
// Process a large JSON array without loading it all into memory
async function processLargeArray(filePath) {
const jsonStream = createReadStream(filePath)
.pipe(parser())
.pipe(streamArray());
for await (const { value } of jsonStream) {
// Process each item individually
console.log(value);
}
}
Deep Cloning Objects with JSON
A quick (but limited) way to deep clone a plain object is to serialize then parse it:
const original = { a: 1, b: { c: [1, 2, 3] } };
const clone = JSON.parse(JSON.stringify(original));
clone.b.c.push(4);
console.log(original.b.c); // [1, 2, 3] โ unaffected
console.log(clone.b.c); // [1, 2, 3, 4]
Limitations of JSON cloning:
- Loses functions, undefined, symbols
- Converts Dates to strings
- Cannot handle circular references (throws error)
- Loses prototype chain
- Map and Set become empty objects
For production code, prefer structuredClone() (available in modern browsers and Node.js 17+) which handles Dates, Maps, Sets, and circular references correctly:
const original = {
date: new Date(),
map: new Map([['a', 1]]),
set: new Set([1, 2, 3])
};
const clone = structuredClone(original);
console.log(clone.date instanceof Date); // true
console.log(clone.map instanceof Map); // true
Performance Optimization
For performance-critical applications, consider these optimization strategies:
Lazy Parsing with Reviver
Use the reviver to skip processing of unneeded data:
// Only extract specific fields from large JSON
const neededFields = new Set(['id', 'name', 'status']);
const result = JSON.parse(largeJson, (key, value) => {
// Skip nested objects we don't need
if (key === 'metadata' || key === 'history') {
return undefined; // Removes from result
}
return value;
});
Web Workers for Heavy Parsing
Move JSON parsing off the main thread to prevent UI blocking:
// worker.js
self.onmessage = (e) => {
const data = JSON.parse(e.data);
self.postMessage(data);
};
// main.js
const worker = new Worker('worker.js');
worker.onmessage = (e) => {
console.log('Parsed data:', e.data);
};
// Parse in background
worker.postMessage(largeJsonString);
Performance Benchmarks
Typical parsing speeds on modern hardware (Node.js v20):
| JSON Size | Parse Time | Stringify Time |
| 1 KB | <0.1 ms | <0.1 ms |
| 100 KB | ~1 ms | ~2 ms |
| 1 MB | ~10 ms | ~15 ms |
| 10 MB | ~80 ms | ~120 ms |
| 100 MB | ~800 ms | ~1200 ms |
For JSON larger than 10MB, consider streaming parsers or paginated APIs to avoid memory issues and UI freezing.
Reading JSON Files in Node.js
// Modern Node.js (v20+) โ import assertion
import data from "./config.json" with { type: "json" };
// Node.js v17+ โ import assertion (older syntax)
import data from "./config.json" assert { type: "json" };
// All Node.js versions โ synchronous
import { readFileSync } from "fs";
const raw = readFileSync("./data.json", "utf8");
const data = JSON.parse(raw);
// All Node.js versions โ async
import { readFile } from "fs/promises";
const raw = await readFile("./data.json", "utf8");
const data = JSON.parse(raw);
// Using require (CommonJS)
const config = require('./config.json');
Try Our JSON Tools
Need to validate, format, or debug JSON before working with it in JavaScript?