How to use JSON.stringify with a Replacer Function In Javascript
In this approach, we’re using JSON.stringify method with a replacer function to transform specific properties of objects during JSON serialization. Here, the replacer function checks if a property’s value is a string and converts it to uppercase.
Syntax:
JSON.stringify(value, [replacer, [space]])
Example: The below example uses JSON.stringify with a Replacer Function to JSON stringify an array of objects in JavaScript.
const data = [
{
language: 'JavaScript',
category: 'Web Development'
},
{
language: 'Python',
category: 'Data Science'
},
{
language: 'Java',
category: 'Software Development'
}
];
const res = JSON.stringify(data, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});
console.log(res);
Output:
[
{"language":"JAVASCRIPT","category":"WEB DEVELOPMENT"},
{"language":"PYTHON","category":"DATA SCIENCE"},
{"language":"JAVA","category":"SOFTWARE DEVELOPMENT"}
]
How to JSON Stringify an Array of Objects in JavaScript ?
In JavaScript, the array of objects can be JSON stringified for easy data interchange and storage, enabling handling and transmission of structured data. The below approaches can be utilized to JSON stringify an array of objects.
Table of Content
- Using JSON.stringify with a Replacer Function
- Using a Custom Function for JSON Stringify