小编典典

将JSON数据保存到文本文件并读取

json

是否可以将JSON数据保存到本地文本文件中?因此,稍后我可以通过加载该文件再次使用它,并取回存储的JSON数据。其实我真正想做的是在文本文件中导出JSON数据,以便以后可以用作import.Any的建议或解决方案?

这是我要用于导出到文本的一些示例。

http://jsfiddle.net/k56eezxp/

var data = new Blob([text], {type: 'text/plain'});

阅读 369

收藏
2020-07-27

共1个答案

小编典典

是否可以将JSON数据保存到本地文本文件中?

是。当前,链接的jsfiddle处的JavaScript创建一个.txt文件,而不是有效JSON文件。

您可以使用try..catch..finallyJSON.parse()检查<textarea>element上的输入是否有效JSON。如果.valueof
<textarea>有效,请使用或MIME 属性设置为的构造函数JSON创建。并且,否则通知用户输入无效。Blob URL``Blob``File``type``"application/json"``URL.createObjectURL()``JSON

(function () {



 let file, url, reader = new FileReader;



 function createJSONFile(json) {

    let e = void 0;

    try {

      JSON.parse(json)

    } catch (err) {

      e = err;

      code.textContent = e;

    }

    finally {

      if (e) {

        code.classList.add("invalid");

        return "Invalid JSON";

      }

      else {

        code.classList.remove("invalid");

        file = new File([json], "info.json", {type:"application/json"});

        url = URL.createObjectURL(file);

        return url;

      }

    }

  };



  function revokeBlobURL() {

    window.removeEventListener("focus", revokeBlobURL);

    URL.revokeObjectURL(url);

    if (file.close) {

      file.close();

    }

  }



  function readJSON(e) {

    reader.readAsText(input.files[0]);

  }



  let create = document.getElementById("create"),

    textbox = document.getElementById("textbox"),

    code = document.querySelector("code"),

    input = document.querySelector("input[type=file]"),

    pre = document.querySelector("pre");



  create.addEventListener("click", function () {

    var link = document.createElement("a");

    link.setAttribute("download", "info.json");

    var json = createJSONFile(textbox.value);

    if (json !== "Invalid JSON") {

      link.href = json;

      document.body.appendChild(link);

      code.textContent = "Valid JSON";

      link.click();

      window.addEventListener("focus", revokeBlobURL);

    } else {

      code.textContext = json;

    }

  }, false);



  reader.addEventListener("load", function() {

    pre.textContent = JSON.stringify(reader.result, null, 2);

  });



  input.addEventListener("change", readJSON);

})();


code {

  display:block;

  width: 350px;

  height: 28px;

  border: 1px dotted green;

  padding: 4px;

  margin: 4px;

  color: green;

}



.invalid {

  border: 1px dotted red;

  color: red;

}



pre {

  background: #eee;

  width: 350px;

  height: 350px;

  border: 1px solid darkorange;

}


<textarea id="textbox" placeholder="Input valid JSON"></textarea><br>

<button id="create">Create file</button>

<br>

<code></code>

<input type="file" accept=".json" />

<pre></pre>
2020-07-27