JavaScript Convert an array to JSON


An array is a special object in JavaScript, that stores multiple types of values which means that it can store an integer value, string value, or float value simultaneously. There are various ways to create an array in JavaScript, following is the syntax to do so −

var array = [value1, value2, value3,…];
or
var array = new Array(size);
or
var array = new Array(element1, element2,…);

Where the value is the elements of the array so it can be of any type.

The JSON is an object notation in JavaScript that is used to represent structured data based on the JavaScript object syntax. It is commonly used to transmit data in web applications. Let’s say if we send any data from the server to the client then it will be displayed on the web page and vice-versa.

Note − The JSON can’t be called or constructed.

In the article we will look at how to convert an array into JSON.

Using JSON.stringify() method

The JSON.stringify() method is used to convert a JavaScript value to a JSON string. Or we say that it is used to convert a JavaScript object into a string.

As we know that in JavaScript an array is an object so we can pass an array object as an argument in this method as shown below −

JSON.stringify(array);

Example

Following is the program to convert an array into JSON −

<!DOCTYPE html> <html lang="en"> <head> <title>Array to JSON</title> </head> <body> <script> //declare an array let array = new Array(5); //initialize value array[0] = 10; array[1] = 20; array[2] = 30; array[3] = 40; array[4] = 50; //calculate the array length let len = array.length; document.write("An array elements are: "); for(let i = 0; i<len; i++) { document.write(array[i] + " "); } //using JSON.stringify method - document.write("<br>Array to JSON: " + JSON.stringify(array)); </script> </body> </html>

In the above program, firstly, we declare an array with a fixed size and then we initialize the value. And by using for loop we print the array elements.

We then used JSON.stringify(array) method to convert an array to JSON and pass an array as an argument of the method. Using the document.write() method we print the output.

Let’s use HTML and CSS with JavaScript −

HTML file(index.html)

This is the HTML file, and the file must be saved with a .html extension, through the HTML we will build the structure of the content page, and we will create a button, heading, paragraphs, span tag, etc.

index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Array to JSON</title> </head> <body> <h1>JavaScript program to convert an Array to JSON.</h1> <p>Click on the below button to convert an array to JSON.</p> <button id = 'btn'>Convert to JSON</button><br> <span id = 'result'></span> <span id = 'result1'></span> </body> </html>

CSS file(style.css)

By using CSS we will manage the styling of the whole HTML page. All the HTML elements within the page are styled by customizing the size, colors, positions etc.

Following is the snippet of code to connect the CSS file with the HTML file −

<link rel = ‘stylesheet’ href = ‘style.css’>

style.css

button{ width: 150px; height: 30px; cursor: pointer; } span{ position: relative; top: 20px; color: green; font-size: 25px; }

JavaScript file(index.js)

In JavaScript we write a program to manage a certain activity, we will fetch the button by using a query selector. Next, use the onclick event to convert an array into JSON, as when a user clicks on the button the array will convert into JSON.

Following is the snippet of code to connect the JavaScript file with the HTML file −

<script src = ‘index.js’>

index.js

let colors = ["red", "black", "green", "yellow"]; let res = document.getElementById('result'); res.innerHTML = "An array elements are: " + colors; let btn = document.querySelector('#btn'); btn.onclick = function() { document.getElementById('result1').innerHTML = "<br>Array to JSON is: " + JSON.stringify(colors); }

Example

On Executing above program HTML, CSS, and JavaScript

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Array to JSON</title> <style> button{ width: 150px; height: 30px; cursor: pointer; } span{ position: relative; top: 20px; color: green; font-size: 25px; } </style> </head> <body> <h1>JavaScript program to convert an Array to JSON.</h1> <p>Click on the below button to convert an array to JSON.</p> <button id = 'btn'>Convert to JSON</button><br> <span id = 'result'></span> <span id = 'result1'></span> <script> let colors = ["red", "black", "green", "yellow"]; let res = document.getElementById('result'); res.innerHTML = "An array elements are: " + colors; let btn = document.querySelector('#btn'); btn.onclick = function() { document.getElementById('result1').innerHTML = "<br>Array to JSON is: " + JSON.stringify(colors); } </script> </body> </html>

In the above program, we have used HTML, CSS, and JavaScript. In HTML we have created buttons, heading, paragraphs, span tags, etc. and in CSS we wrote a code that will style the HTML buttons, headings, paragraphs, etc.

In JavaScript, by using the query selector we fetch the button, and with document.getElementById() we fetch the span tag value. And later on, we used the onclick event and JSON.stringify() method to convert an array into JSON. When the user clicks on the button then an array will convert into JSON, by using the innerHTML method we print the output.

Updated on: 02-Nov-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements