Q. Explain JSON.stringify() in Javascript
JSON.stringify()
is a method in JavaScript that converts a JavaScript object or value into a JSON string. JSON stands for JavaScript Object Notation, and it's a lightweight data-interchange format that's easy for humans to read and write and easy for machines to parse and generate.
Here's how JSON.stringify()
works:
- If the input value is an object (including arrays, dates, and plain objects),
JSON.stringify()
will serialize it into a JSON string. - If the input value is not an object (like a string, number, boolean, or null), it will be coerced into its corresponding primitive value, and that value will be returned.
- If the input value is
undefined
, a function, or a symbol, it will be excluded from the resulting JSON string (or replaced withnull
if it's a property value within an object).
Here's a simple example:
javascriptconst obj = {
name: "John",
age: 30,
isAdmin: true,
hobbies: ["reading", "coding", "hiking"],
address: {
city: "New York",
zip: "10001"
}
};
const jsonString = JSON.stringify(obj);
console.log(jsonString);
This will output:
Result{"name":"John","age":30,"isAdmin":true,"hobbies":["reading","coding","hiking"],"address":{"city":"New York","zip":"10001"}}
You can also provide a "replacer" function or an array of property names to specify which properties should be included or how they should be transformed during serialization. Additionally, you can specify a "space" parameter to add whitespace for improved readability of the resulting JSON string.
javascriptconst obj = {
name: "John",
age: 30,
isAdmin: true,
hobbies: ["reading", "coding", "hiking"],
address: {
city: "New York",
zip: "10001"
}
};
const jsonString = JSON.stringify(obj, ['name', 'hobbies'], 2);
console.log(jsonString);
This will output:
Result{ "name": "John", "hobbies": [ "reading", "coding", "hiking" ] }
This is particularly useful when you want to exclude certain properties or control the structure of the resulting JSON string.