Convert An Array To JSON In JavaScript

To convert an array to JSON in JavaScript, use the JSON.stringify() method. This method accepts an argument and converts it to a JSON string.

Let’s discuss this method in detail below.

convert an array to JSON in JavaScript

Convert An Array To JSON In JavaScript

The JSON.stringify() method is used to convert an array to JSON in JavaScript. This method accepts an argument and converts it to a JSON string. The following example shows how to use this method:

var myArray = ['John', 'Smith', 'Peter'];

console.log(JSON.stringify(myArray));

The output of the above code will be:

[“John”,”Smith”,”Peter”]

You can parse this JSON string back to an array using the JSON.parse() method. The following example shows how to use this method:

var myArray = ['John', 'Smith', 'Peter'];

var json = JSON.stringify(myArray);

var myParsedArray = JSON.parse(json);

console.log(myParsedArray);

The output of the above code will be:

[“John”,”Smith”,”Peter”]

As you can see from the output, the JSON.parse() method has successfully parsed the JSON string back to an array.

If there are any undefined values, or functions in the array, they will be converted to null by the JSON.stringify() method. The following example shows how this works:

var myArray = ['John', undefined, 'Smith', null, 'Peter'];

console.log(JSON.stringify(myArray));

The output of the above code will be:

[“John”,null,”Smith”,null,”Peter”]

As you can see, the undefined values in the array have been converted to null.

Similarly any function in the array will also be converted to null. The following example shows how this works:

var myArray = ['John', function() {}, 'Smith', null, 'Peter'];

console.log(JSON.stringify(myArray));

The output of the above code will be:

[“John”,null,”Smith”,null,”Peter”]

So, as you can see, the JSON.stringify() method is very useful for converting an array to JSON in JavaScript.

Leave a Reply