- Post History
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
on 06-05-2021 11:16 AM
We all know the primary purpose for JSON.stringify(), The JSON.stringify() method converts a JavaScript object or value to a JSON string. However there are 2 interesting parameter that can be used to simplify developer's job. One can be used to filter the JSON and other can be used to indent it.
Here is Syntax
JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
The replacer parameter
The replacer parameter can be either a function or an array.
As a function, it takes two parameters: the key and the value being stringified. The object in which the key was found is provided as the replacer's this parameter.
Example replacer, as a function
function replacer(key, value) {
// Filtering out properties
if (typeof value === 'string') {
return undefined;
}
return value;
}
var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
JSON.stringify(foo, replacer);
// '{"week":45,"month":7}'
Example replacer, as an array
If replacer is an array, the array's values indicate the names of the properties in the object that should be included in the resulting JSON string.
JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}', only keep "week" and "month" properties
The space argument
The space argument may be used to control spacing in the final string.
- If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10).
- If it is a string, successive levels will be indented by this string (or the first ten characters of it).
JSON.stringify({ a: 2 }, null, ' ');
// '{
// "a": 2
// }'
Using a tab character mimics standard pretty-print appearance:
JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
// returns the string:
// '{
// "uno": 1,
// "dos": 2
// }'
Useful Resources:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
- 13,926 Views