Introduction
Javascript is a text-based programming language used on both the client and server sides to create interactive web pages. It adds interactive elements to websites that keep users interested, whereas HTML and CSS are languages that give web pages structure and style.
In this blog, we will discuss the conversion of Javascript Array to Json in deep detail. Let’s start going!

See, Javascript hasOwnProperty
JSON.stringify()
The method JSON.stringify() converts a JavaScript Array to JSON string, optionally replacing values if a replacer function or replacer array is specified or optionally including only the specified properties.
The syntax of JSON.stringify() is:-
🚀 JSON.stringify(value)
🚀 JSON.stringify(value, replacer)
🚀 JSON.stringify(value, replacer, space)
Parameter in JSON.stringify()
The parameter used in JSON.stringify are:-
🤖 value: It is the value to be converted into a string.
🤖 replacer: It is the optional parameter. The replacer can be a function that modifies the stringification process's behavior or an array that acts as a filter for the properties of the value object's value objects to be included in the JSON string.
🤖 space: It is also an optional parameter. A number or string that is used to add white space, such as indentation and line breaks, to the output JSON string to make it easier to read.
Example of Converting Javascript Array to JSON.
The below example converts the javascript array to JSON:-
JSON.stringify([1, 2, 3, 4, 5]); // Output is ‘[1,2,3,4,5]’
JSON.stringify([1, "true", true]); // Output is ‘[1,”true”,true]’
JSON.stringify({ x: 6}); // Output is ‘{x:6}’
Using Function as Replacer in JSON.stringify()
The below example is used to filter the Object using the replacer parameter of the JSON.stringify() as a function:-
function replacer(key, value)
{
// Filtering out properties
if (typeof value === "string")
{
return undefined;
}
return value;
}
const func = {
foundation: "Toyota",
model: "square",
week: 35,
transport: "car",
month: 12,
};
JSON.stringify(func, replacer);
Output
'{"week":35,"month":12}'
Using Array as Replacer in JSON.stringify()
The below example is used to filter the Object using the replacer parameter of the JSON.stringify() as an array:-
const func = {
foundation: "Toyota",
model: "square",
week: 35,
transport: "car",
month: 12,
};
JSON.stringify(foo, ["week", "month"]);
Output
'{"week":35,"month":12}'
Using the Space Parameter of JSON.stringify()
The space parameter of the JSON.stringify() is used to indent the output with the extra spaces.
console.log(JSON.stringify({ a: 2 }, null, " "));
Output
{
"a": 2
}
Using a tab character simulates the appearance of pretty standard print:
console.log(JSON.stringify({ a: 1, b: 2 }, null, "\t"));
Output
{
"a": 1,
"b": 2
}