I.Rayetzki I.Rayetzki - 1 year ago 58
HTML Question

Generate a json file from data got after user adds it to the webpage

I want to append inforation to a json file, when something is done on my webpage. For example, when a button clicked , i want information from my textarea be added to a json "message" field. The same with name and e-mail. How can i do that using JS/jQuery?

Answer Source

var info = {};

function generateNewData(attribute) {
  info[attribute] = $('#' + attribute).val();

function showJSON() {
    JSON.stringify(info, null, 2)

function downloadJSON() {
  saveData(info, 'my-json-filename.json');

function saveData(data, fileName) {
    let a = document.createElement("a");
    a.style = "display: none";
    let json = JSON.stringify(data, null, 2), // remove ', null, 2' if you don't want indentation
        blob = new Blob([json], { type: "octet/stream" }),
        url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type='text' id='name' onkeypress='generateNewData("name")'/>
<br />
<input type='email' id='email' onkeypress='generateNewData("email")'/>
<br />
<textarea id='message' onkeypress='generateNewData("message")'></textarea>

<pre id='json'></pre>

<button onClick='downloadJSON();'>Download JSON</button>

So for example if we want to generate a JSON object after the user writes anything new then we can do the following snippet...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download