Convert an Array to JSON in JavaScript
Last Updated :
07 Oct, 2024
Given a JavaScript Array and the task is to convert an array to JSON Object.
Below are the approaches to convert an array to JSON using JsvaScript:
JSON.stringify() method
The use of JSON is to exchange data to/from a web server. While sending data to a web server, the data need to be a string. This method converts the javascript Object(array in this case) into JSON_string.
Syntax:
JSON.stringify(Javascript Object)
Example 1: This example converts the JS array to JSON String using JSON.stringify() method.
html
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript | Convert array to JSON.
</title>
</head>
<body style="text-align:center;" id="body">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-size: 16px;">
</p>
<button onclick="gfg_Run()">
Convert
</button>
<p id="GFG_DOWN" style="color:green;
font-size: 20px; font-weight: bold;">
</p>
<script>
let el_up = document.getElementById("GFG_UP");
let el_down = document.getElementById("GFG_DOWN");
let array = [34, 24, 31, 48];
el_up.innerHTML = "Array = [" + array + "]";;
function gfg_Run() {
el_down.innerHTML = "JSON_String = '" + JSON.stringify(array) + "'";
}
</script>
</body>
</html>
Output:
Object.assign() method
This method copies the values of all properties owned by enumerables from source objects(one or more) to a target object.
Syntax:
Object.assign(target, ...sources)
Example: This example converts the JS array to JSON Object using Object.assign() method.
html
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript | Convert array to JSON.
</title>
</head>
<body style="text-align:center;" id="body">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-size: 16px;">
</p>
<button onclick="gfg_Run()">
Convert
</button>
<p id="GFG_DOWN" style="color:green;
font-size: 20px; font-weight: bold;">
</p>
<script>
let el_up = document.getElementById("GFG_UP");
let el_down = document.getElementById("GFG_DOWN");
let array = [34, 24, 31, 48];
el_up.innerHTML = "Array = [" + array + "]";;
function gfg_Run() {
el_down.innerHTML =
"JSON Object = " + JSON.stringify(Object.assign({}, array));
}
</script>
</body>
</html>
Output: