Convert a JavaScript array into JSON

Introduction

JavaScript Object Notation or commonly known as JSON is a popular way of interchanging data. It is language independent and most of the modern programming languages support generating and parsing JSON. It is used to interact with a web server, meaning for sending and receiving data. When data is sent to a server, it should be a string. The JSON object in JavaScript comes with few very useful functions. One of these functions is stringify() function.

The stringify() is used to convert JavaScript code into a string. We can use the stringify() function to convert object, date, and even array into a string. In this tutorial, we will discuss how to use the stringify() function to convert a JavaScript array into JSON.

JSON.stringify()

Observe the following JavaScript code.

let arr = [ "John", "Mike", "Sam", "Lisa", "Kane", "Don", "Luis", "Mimi" ];

let str = JSON.stringify(arr);

console.log(str); // "[ "John", "Mike", "Sam", "Lisa", "Kane", "Don", "Luis", "Mimi" ]"

console.log(typeof(str)); // string

The array is passed as a parameter to the stringify() function. It converts the array into a plain string. But to convert the array into JSON format, we need to pass it to the stringify() function enclosed in curly brackets accompanied by the spread operator.

Observe the following code.

let arr = [ "John", "Mike", "Sam", "Lisa", "Kane", "Don", "Luis", "Mimi" ];

let str = JSON.stringify({...arr});

console.log(str); // "{"0":"John","1":"Mike","2":"Sam","3":"Lisa","4":"Kane","5":"Don","6":"Luis","7":"Mimi"}"

console.log(typeof(str)); // string

Now it is time to run our code to see the result. So let’s see it…

The string returned by the stringify() function is as follows:

"{
"0": "John",
"1": "Mike",
"2": "Sam",
"3": "Lisa",
"4": "Kane",
"5": "Don",
"6": "Luis",
"7": "Mimi"
}"

The string is in a proper JSON format.

So we have successfully able to convert a JavaScript array into a JSON formatted string.

Leave a Reply

Your email address will not be published. Required fields are marked *