JSON.stringify() is a built-in JavaScript method that converts JavaScript objects, arrays, and primitive values into JSON strings. This process is called serialization and is essential for storing data, sending data over networks, and working with APIs.
Whether you're building a web application, working with REST APIs, or storing data locally, understandingJSON.stringify() is fundamental to JavaScript development. It's the counterpart to JSON.parse(), which converts JSON strings back into JavaScript objects.
Basic Syntax
JSON.stringify(value, replacer, space)
value: The object, array, or primitive to convert
replacer (optional): Function or array to filter/transform values
space (optional): Number or string for formatting/indentation
Simple Examples
Converting an Object
const device = {
hostname: 'router-01',
ipAddress: '192.168.1.1',
port: 443,
active: true
};
const jsonString = JSON.stringify(device);
console.log(jsonString);
// Output:
// {"hostname":"router-01","ipAddress":"192.168.1.1","port":443,"active":true}You can also use our JSON Formatter tool to format and beautify JSON strings online without writing any code.
Converting an Array
const protocols = ['SSH', 'HTTPS', 'SNMP']; const jsonString = JSON.stringify(protocols); console.log(jsonString); // Output: ["SSH","HTTPS","SNMP"]
Learn more about working with JSON arrays in our comprehensive guide.
Pretty Printing (Formatting)
Use the third parameter to add indentation and make JSON readable. This is similar to what ourJSON Formatter tool does:
const device = {
hostname: 'router-01',
config: {
port: 443,
protocol: 'HTTPS'
}
};
// Indent with 2 spaces
const formatted = JSON.stringify(device, null, 2);
console.log(formatted);
// Output:
// {
// "hostname": "router-01",
// "config": {
// "port": 443,
// "protocol": "HTTPS"
// }
// }You can use a number (spaces) or a string (like '\t' for tabs).
Using the Replacer Parameter
Filter Properties with Array
const device = {
hostname: 'router-01',
ipAddress: '192.168.1.1',
internalId: 'secret-123',
port: 443
};
// Only include specific properties
const jsonString = JSON.stringify(device, ['hostname', 'ipAddress', 'port']);
console.log(jsonString);
// Output: {"hostname":"router-01","ipAddress":"192.168.1.1","port":443}
// 'internalId' is excludedTransform Values with Function
const device = {
hostname: 'router-01',
password: 'secret123',
port: 443
};
// Hide sensitive data
const jsonString = JSON.stringify(device, (key, value) => {
if (key === 'password') {
return '***HIDDEN***';
}
return value;
}, 2);
console.log(jsonString);
// Output:
// {
// "hostname": "router-01",
// "password": "***HIDDEN***",
// "port": 443
// }Handling Special Cases
Undefined Values
undefined values are omitted from objects:
const obj = { a: 1, b: undefined, c: 3 };
JSON.stringify(obj);
// Output: {"a":1,"c":3}Functions
Functions are not serialized:
const obj = { a: 1, fn: function() {} };
JSON.stringify(obj);
// Output: {"a":1}Dates
Dates are converted to ISO strings:
const obj = { timestamp: new Date('2025-01-09') };
JSON.stringify(obj);
// Output: {"timestamp":"2025-01-09T00:00:00.000Z"}Circular References
Throws an error:
const obj = {};
obj.self = obj;
JSON.stringify(obj); // Error: Converting circular structure to JSONCommon Use Cases
1. Sending Data to API
const data = { hostname: 'router-01', port: 443 };
fetch('/api/devices', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});Test your API endpoints with our API Tester tool.
2. Storing in localStorage
const settings = { theme: 'dark', notifications: true };
localStorage.setItem('settings', JSON.stringify(settings));
// Retrieve and parse later
const stored = localStorage.getItem('settings');
const settings = JSON.parse(stored);Use JSON.parse() to convert the stored string back to an object.
3. Deep Cloning Objects
const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));
// Note: This only works for simple objects without functions/datesValidate your JSON structure with our JSON Validator before using stringify/parse for cloning.
Best Practices
- •Use try-catch: Wrap in error handling for circular references or large objects
- •Pretty print during development: Use
JSON.stringify(obj, null, 2)for debugging, or use our JSON Formatter for quick formatting - •Filter sensitive data: Use replacer function to exclude passwords or tokens
- •Consider performance: Stringify is synchronous and can block for large objects. Use ourJSON Minifier to reduce file size for production
- •Validate before parsing: Always validate JSON strings with ourJSON Validator before calling JSON.parse()
JSON Tools
Continue Learning
External References
- •MDN - JSON.stringify() - Official documentation
- •JSON.org - JSON format specification