How To Create JSON String From A Java Script Array

admin_img Posted By Bajarangi soft , Posted On 08-10-2020

In Java Script we can convert a java script arrays into a string with JSON.stringify().so today we discuss how to create json string form a java script array .

How To Create JSON String From A Java Script Array

A common use of JSON is to exchange data to/from a web server.

When sending data to a web server, the data has to be a string.

Convert a JavaScript object into a string with JSON.stringify().
 

Stringify a JavaScript Array

It is also possible to stringify JavaScript arrays:

Imagine we have this array in JavaScript:

var arr = [ "John", "Peter", "Sally", "Jane" ];

Use the JavaScript function JSON.stringify() to convert it into a string.

var myJSON = JSON.stringify(arr);

The result will be a string following the JSON notation.

myJSON is now a string, and ready to be sent to a server:

Example(1)

var arr = [ "John", "Peter", "Sally", "Jane" ];
var myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;


Complete Code For Creating JSON String From A JavaScript Array

<!DOCTYPE html>
<html>
<head>
    <title>How To Create JSON String From A JavaScript Array</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>
<div class="container">
    <br>
    <div class="text-center">
        <h1 id="color" style="color: tomato">How To Create JSON String From A JavaScript Array</h1>
    </div>
    <br>
    <div class="well">
        <h2 id="demo1"></h2>

    </div>

    <script>

        var arr = [ "John", "Peter", "Sally", "Jane" ];
        var myJSON = JSON.stringify(arr);
        document.getElementById("demo1").innerHTML = myJSON;

    </script>
</div>
</body>
</html>

Related Post