栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

是。当前,链接的jsfiddle处的Javascript创建一个

.txt
文件,而不是有效
JSON
文件。

您可以使用

try..catch..finally
JSON.parse()
检查
<textarea>
element上的输入是否有效
JSON
。如果
.value
of
<textarea>
有效,请使用或MIME 属性设置为的构造函数
JSON
创建。并且,否则通知用户输入无效。
BlobURL``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;      pre.textContent = e;    }    finally {      if (e) {        pre.classList.add("invalid");        return "Invalid JSON";      }      else {        pre.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"),    pre = document.querySelector("pre"),    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);      pre.textContent = "Valid JSON";      link.click();      window.addEventListener("focus", revokeBlobURL);    } else {      pre.textContext = json;    }  }, false);  reader.addEventListener("load", function() {    pre.textContent = JSON.stringify(reader.result, null, 2);  });  input.addEventListener("change", readJSON);})();pre {  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><pre></pre><input type="file" accept=".json" /><pre></pre>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/392376.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号