The JSON.stringify() function is used to convert JavaScript object, array, or value to a JSON string.
Syntax
JSON.stringify(value, replacer, space)
Example 1: Convert an Array to JSON
Visual Representation
let arr = [
'krunal',
'ankit',
'rushabh'
]
jsonData = JSON.stringify(arr)
console.log(jsonData)
console.log(typeof jsonData === 'string')
Output
["krunal","ankit","rushabh"]
true
Example 2: Array to JSON with indexes as keys
Visual Representation
To convert an array into a JSON object with index keys, use the Object.assign() method in conjunction with the JSON.stringify function.
let arr = ["krunal", "ankit", "rushabh"];
let jsonData = JSON.stringify(Object.assign({}, arr));
console.log(jsonData);
Output
{"0":"krunal","1":"ankit","2":"rushabh"}
Example 3: Converting each element in an array to json
Visual Representation
const arr = [25, 50, 75, 100]
const jsonString = arr.map(item => JSON.stringify(item))
console.log(jsonString)
Output
["25", "50", "75", "100"]
Example 4: Converting Array to a pretty JSON string
let arr = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
];
let jsonString = JSON.stringify(arr, null, 2);
console.log(jsonString);
Output
[
{
"name": "John",
"age": 30
},
{
"name": "Jane",
"age": 25
}
]