What Does JSON.stringify()
Do?
JSON.stringify()
converts a JavaScript object or value into a JSON-formatted string.
Syntax:
JSON.stringify(value, replacer, space)
- value - The object or value to convert into a JSON string.
- replacer (optional) - A function or array that filters properties before converting.
- space (optional) - A number or string to format the JSON output for readability.
Example Usage
Basic Example
const obj = { name: "John", age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString);
// Output: '{"name":"John","age":30}'
With Arrays
const arr = [1, 2, 3];
console.log(JSON.stringify(arr));
// Output: "[1,2,3]"
With Null Values
const obj = { name: "Alice", age: null };
console.log(JSON.stringify(obj));
// Output: '{"name":"Alice","age":null}'
Why Use JSON.stringify()
?
- To Send Data in HTTP Requests: Required when sending data via
fetch()
in JSON format. - To Store Data Locally: Used to store objects in
localStorage
orsessionStorage
. - For Debugging: Helps convert objects into readable strings for logging.
Example: Sending Data in a Fetch Request
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title: "My Post",
body: "This is the content.",
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data));