Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

296
Visualizações
How do I save the inputs of an HTML form into a JSON file with JavaScript?

As my question already reveals, I am trying to save inputs from an HTML form to a json file - However I only get to save the inputs to the localStorage.

let movies = [];
        const addMovie = (ev)=>{
            ev.preventDefault();
            let movie = {
                id: Date.now(),
                title: document.getElementById('title').value,
                year: document.getElementById('yr').value
            }
            movies.push(movie);
            document.querySelector('form').reset();

            //saving to localStorage
            localStorage.setItem('key', JSON.stringify(movies) );
        }
        document.addEventListener('DOMContentLoaded', ()=>{
            document.getElementById('btn').addEventListener('click', addMovie);
        });

Now, I've already tried the fs.writeFile methods but somehow my pc doesn't want to import fs. So I'm asking if there's another way to write the inputs into JSON or how to fix the import fs bug.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In a web browser, you can invoke download in multiple ways. One of possibilities are window.opening a window, redirection, or creating a link and invoking its click method.

const jsonToDownload = '{"foo":42}'

function download() {
  const aElem = document.createElement("A")
  aElem.href = 'data:application/octet-stream,' + jsonToDownload
  aElem.download = 'filename.json'
  aElem.click()
}
<button onclick=download()>Download</button>

You can use any filename. Just set the download attribute on the link to the filename.

If you want do download binary or large data, using BLOB object might be better idea. It is quite simple – create the BLOB, generate its URL, initiate the download and revoke the URL of the BLOB.

const jsonToDownload = '{"foo":42}'

function download() {
  const blob = new Blob([jsonToDownload, ], {
    type: 'application/json',
  })
  const url = URL.createObjectURL(blob)
  const aElem = document.createElement("A")
  aElem.href = 'data:application/octet-stream,' + jsonToDownload
  aElem.download = 'a'
  aElem.click()
  URL.revokeObjectURL(url)
}
<button onclick=download()>Download</button>

Please note that the snippet above will not probably work, because StackOverflow's iframe usage prohibits this behavior in some browsers. Copy the code in your own HTML file adn try it there.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda