To convert an array to JSON in JavaScript, the code is as follows −
Example
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
</style>
</head>
<body>
<h1>Converting an array to JSON</h1>
<button class="Btn">CLICK HERE</button>
<p class="sample"></p>
<h3>Click the above button to convert the array into JSON</h3>
<script>
let sampleEle = document.querySelector(".sample");
let arr = [22, "A", 1, "HELLO", "J", 9, 22];
sampleEle.innerHTML = arr + "<br>";
document.querySelector(".Btn").addEventListener("click", () => {
sampleEle.innerHTML += JSON.stringify(arr);
});
</script>
</body>
</html>Output

On clicking the “CLICK HERE” button −
