JSON Stringify Guide: Convert Objects to Strings
JSON.stringify() is one of the most used methods in JavaScript development. In this guide, you will learn how to convert JSON objects to strings, understand the options available, and see practical examples you can use today.
Table of Contents
What is JSON.stringify()?
JSON.stringify() is a built-in JavaScript method that converts a JavaScript object or value into a JSON string. It is the inverse ofJSON.parse(), which converts a JSON string back into a JavaScript object.
Every JavaScript developer encounters stringify when working with APIs, local storage, or logging. It serializes complex data structures into a format that can be transmitted, stored, or displayed as plain text.
const user = {
name: "Jane Doe",
age: 28,
roles: ["admin", "editor"],
active: true
};
const jsonString = JSON.stringify(user);
// Result: '{"name":"Jane Doe","age":28,"roles":["admin","editor"],"active":true}'How to Use JSON.stringify()
The basic syntax is straightforward, but JSON.stringify() accepts two optional parameters that give you fine-grained control over the output:
JSON.stringify(value, replacer?, space?)
Basic Usage
Pass any JavaScript value to get its JSON string representation:
// String
JSON.stringify("hello"); // '"hello"'
// Number
JSON.stringify(42); // '42'
// Boolean
JSON.stringify(true); // 'true'
// Array
JSON.stringify([1, 2, 3]); // '[1,2,3]'
// Object
JSON.stringify({ key: "value" }); // '{"key":"value"}'
// null
JSON.stringify(null); // 'null'Pretty Printing with Indentation
The third parameter controls spacing. Pass a number for spaces or a string for a custom indent:
const obj = { name: "Alice", hobbies: ["reading", "coding"] };
// Compact (default)
JSON.stringify(obj);
// '{"name":"Alice","hobbies":["reading","coding"]}'
// Pretty with 2 spaces
JSON.stringify(obj, null, 2);
// {
// "name": "Alice",
// "hobbies": [
// "reading",
// "coding"
// ]
// }
// Custom indent string
JSON.stringify(obj, null, " ");
// Same output as 2 spacesAdvanced Options: Replacer and Space
The replacer parameter lets you filter or transform values during serialization. It can be either an array of allowed property names or a function.
Replacer Array: Include Only Specific Keys
const user = {
id: 1,
name: "Bob",
email: "bob@example.com",
password: "secret123",
ssn: "123-45-6789"
};
// Only include safe fields
JSON.stringify(user, ["name", "email"]);
// '{"name":"Bob","email":"bob@example.com"}'Replacer Function: Transform Values
const data = {
date: new Date("2026-01-15"),
price: 19.99,
name: "Widget"
};
JSON.stringify(data, (key, value) => {
if (value instanceof Date) {
return value.toISOString();
}
return value;
});
// '{"date":"2026-01-15T00:00:00.000Z","price":19.99,"name":"Widget"}'Common Pitfalls and Edge Cases
Knowing what JSON.stringify() handles — and doesn't — will save you from subtle bugs:
undefined, Functions, and Symbols Are Omitted
These values are silently removed from objects. Use a replacer function if you need to preserve them.
Circular References Throw an Error
If an object references itself directly or indirectly, JSON.stringify() throws a TypeError. Use a replacer function or a library like flatted to handle circular structures.
NaN, Infinity, and -Infinity Become null
Non-finite numbers are converted to null rather than throwing. For stricter handling, validate your data before stringifying.
BigInt Values Throw a TypeError
BigInt values cannot be serialized by default. Convert them to numbers or strings first, or implement a custom toJSON method.
Common Use Cases
JSON stringification is essential across many development scenarios:
Local Storage
localStorage only stores strings. Use JSON.stringify() to save objects and JSON.parse() to retrieve them.
API Requests
Stringify request bodies for fetch or axios calls. JSON is the standard format for REST API communication.
Debugging & Logging
Log complex objects as readable strings. Use pretty-printing to inspect deeply nested structures during development.
Deep Cloning
JSON.parse(JSON.stringify(obj)) creates a deep copy of serializable objects. Be aware of the limitations with non-serializable values.
Environment Variables
Store complex configuration as stringified JSON in environment variables, then parse them at runtime for flexible deployment configs.
Data Serialization
Serialize application state for transmission over WebSockets, message queues, or server-sent events.
FAQ
What does JSON.stringify() do?
JSON.stringify() converts a JavaScript object or value into a JSON string. It's the inverse of JSON.parse() and is commonly used to prepare data for storage, API transmission, or logging.
How do I pretty-print JSON with stringify?
Pass a third argument to JSON.stringify(obj, null, 2) where 2 is the number of spaces for indentation. This produces human-readable output with line breaks.
What happens with undefined, functions, or symbols?
JSON.stringify() omits undefined, functions, andSymbol keys during conversion. If you need to preserve them, use a replacer function or handle them before stringifying.
Can I stringify nested objects and arrays?
Yes. JSON.stringify() recursively converts nested objects and arrays. However, it throws an error if it encounters circular references. Use a replacer function or a library like flatted to handle circular structures.
How do I convert JSON to a string online?
Use FormatList's JSON Stringify tool. Paste your JSON object, choose between compact and pretty mode, and copy the escaped string result. No signup required.
Try the JSON Stringify Tool
Convert JSON objects to escaped strings and back. Free, no signup required, and fully client-side.
Try JSON Stringify