Reputation: 353
How do I Create a new json file programmatically using JavaScript?
Given the following snippet, I need to push the info
array into a file.
$("#submit").click(function jsonCreator() {
let nameGetter = document.getElementById("nameINPT").value;
let ageGetter = document.getElementById("ageINPT").value;
let info = {
name: nameGetter,
age: ageGetter,
}
})
Upvotes: 0
Views: 2017
Reputation: 469
JSON.stringify(info)
Will convert your javascript Object to Javascript Object Notation (JSON).
But you can not create a file on the server(or your pc) with javascript running on the client side. As client side javascript does not have access to server file system. But you can create and directly download that file to the client computer like this:
$("#submit").click(function jsonCreator() {
let nameGetter = document.getElementById("nameINPT").value;
let ageGetter = document.getElementById("ageINPT").value;
let info = {
name: nameGetter,
age: ageGetter,
}
var element = document.createElement('a');
element.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(info)));
element.setAttribute('download', 'myfile');
element.style.display e= 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
})
Note: did not have a chance to test the code. But used the solution described here to save the file
Upvotes: 2