JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to convert an array to JSON in JavaScript?

To convert an array to JSON, use JSON.stringify() method. You pass an array to the JSON.stringify() method and it returns a string which is a JSON representation of that array.

let arr = ["x", "y", "z"];

//Convert JavaScript array to JSON
let json = JSON.stringify(arr);
console.log(json); //'["x", "y", "z"]'

//convert JSON to JavaScript array
let parsedArray = JSON.parse(json);
console.log(parsedArray); //["x", "y", "z"]

Note: JSON.stringify() does not modify the original array.

If you want to convert JSON string back to a JavaScript array, then call JSON.parse() method.

It is important to note that if an array element is undefined, null or function, it will be converted to null by the JSON.stringify() method.

let arr = ["x", "y", "z", undefined, null];

//Convert JavaScript array to JSON
let json = JSON.stringify(arr);
console.log(json); //'["x", "y", "z", null, null]'

Recommended Posts