How to save JSON data to hard disk? (or access it with javascript)

Asked

Viewed 608 times

1

I am working on an application to study the syntax of languages used on the web (html, css, javascript and etc...), through a "mini-game" of questions and answers, but my problem has been how to save this 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 is that this way the data is saved only in the browser and if I wanted to take this application elsewhere (my mobile phone for example), I could not.

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

1 answer

4


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:

  • link

  • set the address to be the file you want salvage

  • set a name for the file to be saved

  • automatically click on the link

This way the file is saved automatically

Browser other questions tagged

You are not signed in. Login or sign up in order to post.