JavaScript Object to JSON — Complete Conversion Guide 2026
Introduction
Converting JavaScript objects to JSON strings is a fundamental skill for web developers. Whether you're sending data to an API, storing data in localStorage, or serializing data for transmission, understanding how to properly convert objects to JSON is essential.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
JSON looks similar to JavaScript objects, but with some key differences:
- Keys must be wrapped in double quotes
- Strings must use double quotes (not single quotes)
- No trailing commas allowed
- No functions or methods
- No
undefinedvalues
The JSON.stringify() Method
The primary way to convert a JavaScript object to JSON is using the built-in JSON.stringify() method.
Basic Syntax
JSON.stringify(value, replacer, space)
| Parameter | Description |
|---|---|
value |
The JavaScript object to convert |
replacer |
Optional function or array to transform values |
space |
Optional number or string for indentation |
Basic Example
// JavaScript object
const user = {
name: "John Doe",
age: 30,
city: "New York"
};
// Convert to JSON string
const jsonString = JSON.stringify(user);
console.log(jsonString);
// Output: {"name":"John Doe","age":30,"city":"New York"}
Pretty-Printing JSON
To make JSON more readable, use the space parameter to add indentation:
const user = {
name: "John Doe",
age: 30,
hobbies: ["reading", "swimming", "coding"]
};
// Pretty-print with 2 spaces
const prettyJson = JSON.stringify(user, null, 2);
console.log(prettyJson);
/*
Output:
{
"name": "John Doe",
"age": 30,
"hobbies": [
"reading",
"swimming",
"coding"
]
}
*/
Handling Special Cases
Functions and Undefined
JSON.stringify() ignores functions and undefined values:
const obj = {
name: "John",
greet: function() { console.log("Hi"); },
secret: undefined,
age: 30
};
JSON.stringify(obj);
// Output: {"name":"John","age":30}
Dates
Dates are automatically converted to ISO strings:
const event = {
name: "Meeting",
date: new Date("2026-03-10T10:00:00Z")
};
JSON.stringify(event);
// Output: {"name":"Meeting","date":"2026-03-10T10:00:00.000Z"}
Nested Objects
Nested objects are fully serialized:
const company = {
name: "TechCorp",
address: {
street: "123 Main St",
city: "New York",
zip: "10001"
}
};
JSON.stringify(company);
// Output: {"name":"TechCorp","address":{"street":"123 Main St","city":"New York","zip":"10001"}}
Convert JavaScript Objects to JSON Instantly
Use our free online tool to convert JS objects to JSON strings with pretty-printing options.
Convert NowUsing the Replacer Parameter
The replacer parameter lets you customize which values are serialized:
Array Replacer (Whitelist)
const user = {
name: "John",
password: "secret123",
email: "[email protected]",
age: 30
};
// Only include specific fields
const safeJson = JSON.stringify(user, ["name", "email", "age"]);
console.log(safeJson);
// Output: {"name":"John","email":"[email protected]","age":30}
Function Replacer
const obj = {
price: 100,
tax: 10
};
// Calculate total during serialization
const json = JSON.stringify(obj, (key, value) => {
if (key === "total") {
return this.price + this.tax;
}
return value;
});
Common Errors and Solutions
Circular References
JSON.stringify() throws an error for circular references:
const obj = { name: "John" };
obj.self = obj; // Circular reference
JSON.stringify(obj);
// TypeError: Converting circular structure to JSON
Solution: Use a library like flatted or implement a custom serializer:
// Remove circular references
function safeStringify(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, val) => {
if (val != null && typeof val == "object") {
if (seen.has(val)) return;
seen.add(val);
}
return val;
});
}
Converting JSON Back to Object
To convert a JSON string back to a JavaScript object, use JSON.parse():
const jsonString = '{"name":"John","age":30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Output: John
eval() to parse JSON. Always use JSON.parse() for security.
Common Use Cases
Storing Data in localStorage
// Save to localStorage
const user = { name: "John", preferences: { theme: "dark" } };
localStorage.setItem("user", JSON.stringify(user));
// Retrieve from localStorage
const savedUser = JSON.parse(localStorage.getItem("user"));
API Requests
// Send JSON in fetch request
fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "John", email: "[email protected]" })
});
Best Practices
- Always validate JSON before parsing
- Use try-catch for error handling
- Pretty-print for debugging, minify for production
- Be aware of data types that can't be serialized
- Use schema validation for complex data
Frequently Asked Questions
What's the Difference Between a JavaScript Object and JSON?
JavaScript objects are in-memory data structures with methods and prototypes. JSON is a text-based data format that only stores data (no functions).
Why Do JSON Keys Need Quotes?
JSON is a data format, not code. Requiring quotes ensures consistency and makes parsing simpler across different programming languages.
How to Convert a Map to JSON?
const map = new Map([["key1", "value1"], ["key2", "value2"]]);
const json = JSON.stringify(Object.fromEntries(map));
// Output: {"key1":"value1","key2":"value2"}
Conclusion
Converting JavaScript objects to JSON is straightforward with JSON.stringify(). Understanding its parameters and edge cases will help you serialize data correctly for APIs, storage, and data transmission.
Try our free JavaScript to JSON converter for quick conversions with pretty-printing options.
Ready to Convert?
Use Free ConverterRelated Tools: JSON Formatter · JSON Validator · JSON to JavaScript · JSON Minifier