Convert an Array to JSON using JavaScript


Borislav Hadzhiev

Last updated: Nov 1, 2021


Photo from Unsplash

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.

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.

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.