Json Stringify in JavaScript
JSON.stringify() in JavaScript
What is JSON.stringify()?
JSON.stringify()is a built-in JavaScript method.It converts a JavaScript object or value into a JSON string.
Useful when you want to send data to a server or save it as text.
Syntax
JSON.stringify(value[, replacer[, space]])value: The JavaScript object or value to convert.
replacer (optional): A function or array that alters how objects and values are stringified.
space (optional): Adds indentation, white space, and line breaks to make the output more readable.
Basic Example
const obj = { name: "John", age: 30, city: "New York"};const jsonString = JSON.stringify(obj);console.log(jsonString);// Output: '{"name":"John","age":30,"city":"New York"}'Using the replacer Parameter
As a function to filter or transform values:
const obj = { name: "John", age: 30, city: "New York"};const jsonString = JSON.stringify(obj, (key, value) => { if (typeof value === "number") { return undefined; // exclude numbers } return value;});console.log(jsonString);// Output: '{"name":"John","city":"New York"}'As an array to include only specific keys:
const jsonString = JSON.stringify(obj, ["name", "city"]);console.log(jsonString);// Output: '{"name":"John","city":"New York"}'Using the space Parameter
Makes the JSON output pretty-printed (human-readable):
const jsonString = JSON.stringify(obj, null, 4);console.log(jsonString);/* Output:{ "name": "John", "age": 30, "city": "New York"}*/Summary
| Parameter | Description | Example Usage |
|---|---|---|
value | Object or value to convert to JSON string | JSON.stringify(obj) |
replacer | Function or array to filter/transform properties | JSON.stringify(obj, ['name']) |
space | Number or string for indentation and formatting | JSON.stringify(obj, null, 2) |
If you want, I can help you with examples of converting complex objects or handling circular references!