To convert an array to JSON in JavaScript, pass it to JSON.stringify(). It accepts
any array — of strings, numbers, booleans, objects, or nested arrays — and returns a
JSON-formatted string. For example, JSON.stringify(["a", "b"])
returns '["a","b"]'. Add a third argument, JSON.stringify(value, null, 2),
to pretty-print it with two-space indentation.
const fruits = ["apple", "banana", "cherry"];
const json = JSON.stringify(fruits);
console.log(json);
// '["apple","banana","cherry"]' (a string)
The result is a string, not an array — that is the whole point. You now have a
portable text form you can send in a request body, write to a file, or store in a database
column, and later restore with JSON.parse().
Convert an array of objects to JSON
The same call works for an array of objects — the most common real-world case, such as rows from an API or a database query. Every object is serialised in order:
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Linus" },
];
JSON.stringify(users);
// '[{"id":1,"name":"Ada"},{"id":2,"name":"Linus"}]' Pretty-print the JSON output
JSON.stringify() takes two optional arguments: a replacer and a
space value. Pass null for the replacer and a number (or a string like a
tab) for the space to get readable, indented output:
JSON.stringify(users, null, 2);
// [
// {
// "id": 1,
// "name": "Ada"
// },
// ...
// ] That indentation is exactly what a formatter does. If you would rather paste the array's output and beautify or validate it visually, the JSON formatter and JSON editor do it in your browser, with nothing uploaded.
Common gotchas when stringifying arrays
JSON is a smaller data model than JavaScript, so a few values do not survive the round trip. These are the ones that surprise people:
JSON.stringify([undefined, function () {}, Symbol("x")]);
// '[null,null,null]' -> non-serialisable items become null
JSON.stringify([new Date(0)]);
// '["1970-01-01T00:00:00.000Z"]' -> Date becomes an ISO string
JSON.stringify([NaN, Infinity]);
// '[null,null]'
const a = {};
a.self = a;
JSON.stringify([a]);
// TypeError: Converting circular structure to JSON - undefined, functions, symbols — become
nullinside an array (and are dropped inside an object). - Date — serialised to an ISO 8601 string via its
toJSON()method. - NaN and Infinity — become
null. - BigInt — throws a
TypeError; convert it to a string or number first. - Circular references — throw a
TypeError; break the cycle before stringifying.
Turn the JSON string back into an array
The inverse of JSON.stringify() is JSON.parse(), which reads the text
and returns a live array you can work with again:
const json = '["apple","banana"]';
const arr = JSON.parse(json);
Array.isArray(arr); // true
arr[0]; // "apple"