Convert an Array to JSON using JavaScript

avatar

Borislav Hadzhiev

Mon Nov 01 20211 min read

banner

Photo by Jim Jacob

Convert an Array to JSON using JavaScript #

Use the JSON.stringify() method to convert an array to JSON, e.g. const json = JSON.stringify(arr). The method takes a value, converts it to a JSON string and returns the result.

index.js
const arr = ['a', 'b', 'c']; // โœ… Convert Array to JSON const json = JSON.stringify(arr); console.log(json); // ๐Ÿ‘‰๏ธ '["a", "b", "c"]' console.log(typeof json); // ๐Ÿ‘‰๏ธ "string" // โœ… Parse from JSON back to Array const parsed = JSON.parse(json); console.log(parsed); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c']

We used the JSON.stringify method to convert an array to JSON.

The only parameter we passed to the method is the array.

The method returns a string containing the JSON representation of the array.

If you need to convert the JSON string back to an array, use the JSON.parse() method.

When converting an array to JSON, any undefined values or functions get converted to null.

index.js
const arr2 = [undefined, () => {}]; console.log(JSON.stringify(arr2)); // ๐Ÿ‘‰๏ธ '[null,null]'

Undefined values and functions are not valid JSON, so they automatically get converted to null once stringified.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee