Sometimes, we want to create JSON object dynamically via JavaScript.
In this article, we’ll look at how to create JSON object dynamically via JavaScript.
How to create JSON object dynamically via JavaScript?
To create JSON object dynamically via JavaScript, we can create the object we want.
Then we call JSON.stringify
to convert the object into a JSON string.
For instance, we write
let sitePersonnel = {};
let employees = [];
sitePersonnel.employees = employees;
console.log(sitePersonnel);
let firstName = "John";
let lastName = "Smith";
let employee = {
firstName,
lastName,
};
sitePersonnel.employees.push(employee);
console.log(JSON.stringify(sitePersonnel));
to create the sitePersonnel
object that has various properties.
Then we call JSON.stringify
to convert the sitePersonnel
object into a JSON string.
Conclusion
To create JSON object dynamically via JavaScript, we can create the object we want.
Then we call JSON.stringify
to convert the object into a JSON string.