How to Stringify JSON in JavaScript: Simple Guide
To stringify JSON in JavaScript, use the
JSON.stringify() method, which converts a JavaScript object or value into a JSON string. This is useful for sending data over a network or saving it as text.Syntax
The JSON.stringify() method converts a JavaScript value to a JSON string. It has three parts:
value: The JavaScript object or value to convert.replacer(optional): A function or array to control which properties are included.space(optional): Adds indentation, white space, and line breaks for readability.
javascript
JSON.stringify(value, replacer, space)
Example
This example shows how to convert a JavaScript object into a JSON string with pretty formatting.
javascript
const user = { name: "Alice", age: 25, city: "Wonderland" }; const jsonString = JSON.stringify(user, null, 2); console.log(jsonString);
Output
{
"name": "Alice",
"age": 25,
"city": "Wonderland"
}
Common Pitfalls
Common mistakes when using JSON.stringify() include:
- Trying to stringify functions or undefined values, which are ignored or removed.
- Not handling circular references, which cause errors.
- Forgetting to use the
spaceparameter for readable output.
Example of ignoring functions:
javascript
const obj = { name: "Bob", greet: function() { return "Hi"; } }; console.log(JSON.stringify(obj)); // Output ignores the function
Output
{"name":"Bob"}
Quick Reference
| Parameter | Description |
|---|---|
| value | The object or value to convert to JSON string |
| replacer | Optional function or array to filter properties |
| space | Optional number or string for indentation |
Key Takeaways
Use JSON.stringify() to convert JavaScript objects to JSON strings.
The optional space parameter makes the output easier to read.
Functions and undefined values are ignored during stringification.
Circular references cause errors and must be handled separately.
Use replacer to customize which properties to include.