How to JSON Stringify an Array of Objects in JavaScript ?
Last Updated :
30 Aug, 2024
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.
Using JSON.stringify with a Replacer Function
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.
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"}
]
Using a Custom Function for JSON Stringify
In this approach, we're using a custom function approach2Fn to recursively stringify an array of objects, handling objects, arrays, and primitive values to construct a valid JSON string representation. The function checks the type of each item in the data and applies the stringify logic accordingly.
Syntax:
function customStringify(data) {
// code
return jsonString;
}
Example: The below example uses Custom Function for JSON Stringify to json stringify an array of objects in javascript.
JavaScript
const data = [
{
language: 'JavaScript',
category: 'Web Development'
},
{
language: 'Python',
category: 'Data Science'
},
{
language: 'Java',
category: 'Software Development'
}
];
const res = approach2Fn(data);
console.log(res);
function approach2Fn(data) {
if (Array.isArray(data)) {
const sArr = data.map
(item => approach2Fn(item));
return `[${sArr.join(',')}]`;
} else if (typeof data === 'object'
&& data !== null) {
const sObj = Object.entries(data)
.map(([key, value]) =>
`"${key}":${approach2Fn(value)}`)
.join(',');
return `{${sObj}}`;
} else {
return JSON.stringify(data);
}
}
Output:
[
{"language":"JAVASCRIPT","category":"WEB DEVELOPMENT"},
{"language":"PYTHON","category":"DATA SCIENCE"},
{"language":"JAVA","category":"SOFTWARE DEVELOPMENT"}
]
Using a Custom Serialization Class
This approach involves defining a class with a toJSON
method. The toJSON
method allows you to control how instances of the class are serialized to JSON, giving you fine-grained control over the serialization process.
Example: In this example we defines a CustomSerializable class with a toJSON method for custom serialization. It creates an array of instances, converts it to JSON, and logs the string.
JavaScript
class CustomSerializable {
constructor(language, category) {
this.language = language;
this.category = category;
}
// Custom toJSON method
toJSON() {
return {
language: this.language.toUpperCase(),
category: this.category.toUpperCase()
};
}
}
const data = [
new CustomSerializable('JavaScript', 'Web Development'),
new CustomSerializable('Python', 'Data Science'),
new CustomSerializable('Java', 'Software Development')
];
const jsonString = JSON.stringify(data);
console.log(jsonString);
Output[{"language":"JAVASCRIPT","category":"WEB DEVELOPMENT"},{"language":"PYTHON","category":"DATA SCIENCE"},{"language":"JAVA","category":"SOFTWARE DEVELOPMENT"}]
Similar Reads
Convert JSON String to Array of JSON Objects in JavaScript Converting a JSON string to an array of JSON objects in JavaScript involves transforming a structured text format (JSON) into a usable JavaScript array. This allows developers to work directly with the data, enabling easier manipulation, analysis, and display of information.1. Using JSON.parse() Met
2 min read
How to change JSON String into an Object in JavaScript ? In this article we are going to learn how to change JSON String into an object in javascript, JSON stands for JavaScript object notation. It is the plain format used frequently as a communication medium on the internet. It appears close to OOP language like JavaScript but cannot be accessed like Jav
3 min read
How to Convert String of Objects to Array in JavaScript ? This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored i
3 min read
How to Access Array of Objects in JavaScript ? Accessing an array of objects in JavaScript is a common task that involves retrieving and manipulating data stored within each object. This is essential when working with structured data, allowing developers to easily extract, update, or process information from multiple objects within an array.How
4 min read
How to Move a Key in an Array of Objects using JavaScript? The JavaScript array of objects is a type of array that contains JavaScript objects as its elements.You can move or add a key to these types of arrays using the below methods in JavaScript:Table of ContentUsing Object Destructuring and Map()Using forEach() methodUsing for...of LoopUsing reduce() met
5 min read
How to Convert String to Array of Objects JavaScript ? Given a string, the task is to convert the given string to an array of objects using JavaScript. It is a common task, especially when working with JSON data received from a server or API. Below are the methods that allow us to convert string to an array of objects:Table of ContentUsing JSON.parse()
4 min read
How to convert a map to array of objects in JavaScript? A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods
6 min read
How to parse JSON object using JSON.stringify() in JavaScript ? In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax:
2 min read
How to Push an Array into Object in JavaScript? To push an array into the Object in JavaScript, we will be using the JavaScript Array push() method. First, ensure that the object contains a property to hold the array data. Then use the push function to add the new array in the object.Understanding the push() MethodThe array push() method adds one
2 min read
How to Store an Object Inside an Array in JavaScript ? Storing an object inside an array in JavScript involves placing the object as an element within the array. The array becomes a collection of objects, allowing for convenient organization and manipulation of multiple data structures in a single container. Following are the approaches through which it
3 min read