JSON Stringify
Converting JavaScript objects to JSON strings
🔄 JSON.stringify() Method
JSON.stringify() converts a JavaScript object into a JSON string. This is essential when sending data to APIs or storing data.
// JavaScript object
const obj = {
name: "Alice",
age: 25,
active: true
};
// Convert to JSON string
const jsonString = JSON.stringify(obj);
console.log(jsonString);
// Output: '{"name":"Alice","age":25,"active":true}'
Output:
{"name":"Alice","age":25,"active":true}
Stringify Examples
Objects
Convert objects to JSON
JSON.stringify({key: "value"})
Arrays
Convert arrays to JSON
JSON.stringify([1, 2, 3])
Primitives
Convert basic values
JSON.stringify("hello")
Formatting
Pretty-print JSON
JSON.stringify(obj, null, 2)
🔹 Basic JSON.stringify() Usage
Convert different JavaScript values to JSON:
// Convert different data types
console.log(JSON.stringify("Hello")); // '"Hello"'
console.log(JSON.stringify(42)); // '42'
console.log(JSON.stringify(true)); // 'true'
console.log(JSON.stringify(null)); // 'null'
// Convert array
const fruits = ["apple", "banana", "cherry"];
console.log(JSON.stringify(fruits));
// '["apple","banana","cherry"]'
// Convert object
const person = {
name: "Bob",
age: 30,
married: false
};
console.log(JSON.stringify(person));
// '{"name":"Bob","age":30,"married":false}'
Output:
"Hello"
42
true
null
["apple","banana","cherry"]
{"name":"Bob","age":30,"married":false}
🔹 Pretty Printing JSON
Use the third parameter to format JSON with indentation:
const data = {
user: {
id: 123,
name: "Sarah",
preferences: {
theme: "dark",
notifications: true
},
hobbies: ["reading", "photography"]
}
};
// Compact JSON (default)
console.log(JSON.stringify(data));
// Pretty-printed JSON with 2-space indentation
console.log(JSON.stringify(data, null, 2));
Pretty-printed Output:
{
"user": {
"id": 123,
"name": "Sarah",
"preferences": {
"theme": "dark",
"notifications": true
},
"hobbies": [
"reading",
"photography"
]
}
}
🔹 Filtering Properties
Use the replacer parameter to control which properties are included:
const user = {
id: 123,
name: "Alice",
email: "[email protected]",
password: "secret123",
age: 25,
role: "admin"
};
// Include only specific properties
const publicData = JSON.stringify(user, ["id", "name", "email"]);
console.log(publicData);
// '{"id":123,"name":"Alice","email":"[email protected]"}'
// Use replacer function to exclude sensitive data
const safeData = JSON.stringify(user, (key, value) => {
// Exclude password field
if (key === "password") {
return undefined;
}
return value;
});
console.log(safeData);
Filtered Output:
{"id":123,"name":"Alice","email":"[email protected]"}
{"id":123,"name":"Alice","email":"[email protected]","age":25,"role":"admin"}
🔹 Handling Special Values
JSON.stringify() handles some values in special ways:
const specialValues = {
func: function() { return "hello"; }, // Functions are ignored
undef: undefined, // undefined is ignored
symbol: Symbol("test"), // Symbols are ignored
date: new Date(), // Dates become strings
regex: /pattern/g, // RegExp becomes {}
infinity: Infinity, // Infinity becomes null
nan: NaN // NaN becomes null
};
console.log(JSON.stringify(specialValues, null, 2));
Output:
{
"date": "2024-01-15T10:30:00.000Z",
"regex": {},
"infinity": null,
"nan": null
}
Note: Functions, undefined, and symbols are omitted
🔹 Real-World Examples
Common use cases for JSON.stringify():
📡 Sending API Data
// Prepare data for API request
const formData = {
name: "John Doe",
email: "[email protected]",
preferences: {
newsletter: true,
theme: "light"
}
};
// Convert to JSON for API
const jsonPayload = JSON.stringify(formData);
// Simulate API call
fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: jsonPayload
});
💾 Storing in Local Storage
// Save user settings to localStorage
const userSettings = {
theme: "dark",
language: "en",
notifications: {
email: true,
push: false
}
};
// Convert to JSON string for storage
localStorage.setItem('userSettings', JSON.stringify(userSettings));
// Later, retrieve and parse
const saved = localStorage.getItem('userSettings');
const settings = JSON.parse(saved);
🔹 Custom toJSON() Method
Objects can define their own JSON serialization:
// Custom object with toJSON method
const customObject = {
name: "Custom Object",
secret: "hidden value",
publicData: "visible data",
// Define custom JSON serialization
toJSON() {
return {
name: this.name,
publicData: this.publicData,
serializedAt: new Date().toISOString()
};
}
};
console.log(JSON.stringify(customObject, null, 2));
Output:
{
"name": "Custom Object",
"publicData": "visible data",
"serializedAt": "2024-01-15T10:30:00.000Z"
}