从 html 表单创建 json 文件

Create a json file from a html form


我有一个 html 表单,我想创建一个 json 文件,其中包含在 html 字段中引入的数据。
现在,它在控制台 json-text 中可见,但它不会创建包含此内容的新 json-文件。
另外,我有一个错误,Uncaught ReferenceError: require is not defined。
    // get the form element from dom
    const formElement = document.querySelector('form#forms')

    // convert the form to JSON
    const getFormJSON = (form) => {
      const data = new FormData(form);
      return Array.from(data.keys()).reduce((result, key) => {
        if (result[key]) {
          result[key] = data.getAll(key)
          return result
        }
        result[key] = data.get(key);
        return result;
      }, {});
    };

    // handle the form submission event, prevent default form behaviour, check validity, convert form to JSON
    const handler = (event) => {
      event.preventDefault();
      const valid = formElement.reportValidity();
      if (valid) {
        const result = getFormJSON(formElement);
        // handle one, multiple or no files uploaded
        const images = [result.images].flat().filter((file) => !!file.name)
        // handle one, multiple or no languages selected
        const languages = [result.languages || []].flat();
        // convert the checkbox to a boolean
        const isHappyReader = !!(result.isHappyReader && result.isHappyReader === 'on')

        // use spread function, but override the keys we've made changes to
        const output = {
          ...result,
          images,
          languages,
          isHappyReader
        }
        console.log(output)
      }
    }

    formElement.addEventListener("submit", handler)



    const fs = require('fs');
    const dataNew = JSON.stringify(output);
    fs.writeFile('output.json', dataNew, (err) => {
    if (err) {
        console.log("error")
        throw err;
    }
    console.log("JSON data is saved.");
});
  </script>
</body>

看来你在前端。出于安全考虑,你不能这样写文件。这将导致每个具有一些 JavaScript 的网站都可能将文件写入您的系统,而您真的不希望这样。 另外 fs 是一个在浏览器中不可用的节点 API。

一种选择是从前端下载 JSON 文件,您可以使用以下代码执行此操作:

/**
 * Download a JSON file.
 * @param {sting} filename filename
 * @param {any} obj any serializeable object
 */
function downloadJson(filename, obj) {
  // serialize to JSON and pretty print with indent of 4
  const text = JSON.stringify(obj, null, 4);

  // create anchor tag
  var element = document.createElement("a");
  element.setAttribute(
    "href",
    "data:application/json;charset=utf-8," + encodeURIComponent(text)
  );
  element.setAttribute("download", filename);
  // don't display the tag
  element.style.display = "none";
  // add tag to document
  document.body.appendChild(element);
  // click it: this starts the download
  element.click();
  // remove the tag again
  document.body.removeChild(element);
}

window.addEventListener("DOMContentLoaded", (event) => {
  // Start file download.
  downloadJson("helloWorld.json", { hello: "World" });
});


如果将其添加到您的页面,保存对话框将出现在用户的系统上。这是我要上的 Ubuntu:

这里是下载文件的内容:

Please read on the pros and cons of using an approach like this.