How to save JSON data to the hard drive? (or access them with javascript)

0

I'm working on an application to study the syntax of languages used on the web (html, css, javascript and etc ...) through a question and answer mini-game, but my problem has been how to save that data .

The method I learned is this below:

/* coloque os dados em um array */

var dados = ["mizuk","programação","animes"];

/* guarde os dados recebidos no navegador */

localStorage.setItem("user",JSON.stringify(dados));

/* passe os dados para um novo array */

var user = JSON.parse(localStorage.getItem("user"));

/* imprima no console os dados recebidos */

console.log(" nome: " + user[0] + "\n trabalha com: " 
   + user[1] + "\n e gosta de: " + user[2]);

The problem with this is that in this way the data is saved only in the browser and if I wanted to take that application to another place (my cell phone for example), I would not be able to.

Does anyone know a way to save this data locally or simply access them on the "server" via javascript? (so I can put the questions as JSON files in a folder, and then access with javascript)

    
asked by anonymous 24.02.2018 / 16:31

1 answer

3

You can use the following function:

var dados = ["mizuk","programação","animes"];

function baixarArquivo(name) {
    var link = document.createElement('a');
    link.href = 'data:application/octet-stream;charset=utf-8,' + JSON.stringify(dados);
    link.download = name;
    link.click();
}
<a onclick="baixarArquivo('arquivo.json')">Download</a>

This function will:

  • create a link

  • Set the address as the file you want save

  • Set a name for the file to be saved

  • automatically click on the link

This way the file is automatically saved

    
24.02.2018 / 16:59