是否可以将 JSON 数据保存到本地文本文件中?所以稍后我可以通过加载该文件并取回存储的 JSON 数据来再次使用它。实际上我真正想做的是将 JSON 数据导出到文本文件中,以便稍后可以用作导入。这里有什么建议或解决方案吗?
这是我想用来导出到文本的一些示例。
var data = new Blob([text], {type: 'text/plain'});
最佳答案
Is there possible to save JSON data into local text file?
是的。目前,链接的 jsfiddle 上的 JavaScript 创建了一个 .txt
文件,不是有效的 JSON
文件。
您可以使用try..catch..finally
和JSON.parse()
检查是否输入 <textarea>
元素有效 JSON
。如果.value
的<textarea>
有效JSON
创建Blob URL
使用Blob
或File
带有 MIME 的构造函数 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>
关于javascript - 将 JSON 数据保存到文本文件并读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44038201/