是否可以将JSON数据保存到本地文本文件中?
是。当前,链接的jsfiddle处的Javascript创建一个
.txt文件,而不是有效
JSON文件。
您可以使用
try..catch..finally和
JSON.parse()检查
<textarea>element上的输入是否有效
JSON。如果
.valueof
<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>


