I.Rayetzki I.Rayetzki - 3 months ago 7
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

var info = {};
showJSON();

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

function showJSON() {
  $('#json').html(
    JSON.stringify(info, null, 2)
  );
}

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

function saveData(data, fileName) {
    let a = document.createElement("a");
    document.body.appendChild(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;
    a.click();
    window.URL.revokeObjectURL(url);
};
<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...