How To Convert An Array To Json Using Javascript

Convert an array to json using javascript

While working on web development, there are many times we have to convert an array to json using Javascript. If you still do not know how to convert it, don’t worry! In this tutorial, we’ll show you how to do that in just a few steps.

What is JSON?

JavaScript Object Notation (JSON) is an extremely fast data transfer format between the servers and the clients/web pages. It is a string that has the same format as JavaScript Object literal format. You can read more about JSON here

Our data has to be a string if we want to send it to the web server. That is why in some situations when we want to send our array, we have to convert it into a JSON string/JSON object. 

How to convert an array to JSON using JavaScript 

Method 1: Using JSON.stringify()

This is the simplest method to convert an array into a JSON string. 

Syntax

JSON.stringify(value)

Parameters:

  • value: The value that you want to convert into a JSON string.

Return value: The JSON string representing the value.

Example

We will have the array myArr containing a list of numbers. Now we will apply the JSON.stringify() method to convert it into a string and stored in str. We will also use typeof to check the type of our converted string.

var myArr = [78, 353, 35, 49, 83, 100, 45]; 
var str = JSON.stringify(myArr);  

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

Output: 

[78,353,35,49,83,100,45]
string

Method 2: Using JSON.parse()

After converting your array into a JSON string, you can also do one more step to make it a JSON object. The idea is to use the JSON.parse() method. 

Syntax:

JSON.parse(text, reviver)

Parameters:

  • text: The string to parse
  • reviver (optional): A function that modifies the result before returning. 

Return value: Object, array, string, number, boolean, or null value based on the given JSON text.

Completed code for the example: 

var myArr = [78, 353, 35, 49, 83, 100, 45]; 
var str = JSON.stringify(myArr);  
var obj = JSON.parse(str);  

console.log(obj);
console.log(typeof obj);

Output: 

[78,353,35,49,83,100,45]
object

In our object, the index of our array’s elements are the names and the values of the elements are the values of the names.

Summary

In this tutorial, we have shown you how to convert an array to JSON using JavaScript (JSON string and JSON object). This is one of the most important skills that we should know while working on web development. The ideas are very straightforward: use JSON.stringify() to convert your array into a JSON string and JSON.parse() to convert your JSON string into a JSON object.

Maybe you are interested:

Leave a Reply

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