Skip to content

JavaScript creates JSON Array dynamically

  • by

In JavaScript, you can create a JSON array dynamically by creating a JavaScript array and then using the JSON.stringify() method to convert it into a JSON string.

JavaScript creates JSON Array dynamically example

Simple example code.

<!DOCTYPE html>
<html>
<body>
    <script>
    let people = [
        { "name": "John", "age": 30, "city": "New York" },
        { "name": "Mary", "age": 25, "city": "Los Angeles" },
        { "name": "Bob", "age": 40, "city": "Chicago" }
    ];

    let peopleJSON = JSON.stringify(people);
    console.log(peopleJSON)

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

You can also dynamically create a JSON array by first creating an empty JavaScript array and then adding JSON objects to it using the push() method:

let jsonArray = [];

for (let i = 0; i < 3; i++) {
  let obj = {
    name: "Person " + (i + 1),
    age: Math.floor(Math.random() * 50) + 20,
    city: "City " + (i + 1)
  };
  jsonArray.push(obj);
}

let jsonString = JSON.stringify(jsonArray);
//console.log(jsonString)
console.log(jsonArray)

Output:

JavaScript creates JSON Array dynamically

Do comment if you have any doubts or suggestions on this JS JSON topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading