Convert an Array to JSON using JavaScript


Borislav Hadzhiev

Mon Nov 01 20211 min read


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.

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 #

Use the search field on my Home Page to filter through my more than 1,000 articles.