JavaScript Convert an array to JSON

JavascriptWeb DevelopmentObject Oriented Programming

To convert an array to JSON in JavaScript, the code is as follows −

Example

 Live Demo

<!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 −


raja
Published on 07-May-2020 17:40:10
Advertisements