我有一个 javascript,可以创建并保存一个包含对象数组的 json 文件:
let Animal = {
legs: "",
color: "",
};
let arr[];
let me = Object.create(Animal);
me.legs = "a";
me.color = "b";
arr.push(me);
window.localStorage.setItem("example", JSON.stringify(arr));
exportA();
function exportA()
{
const a = document.createElement("a");
a.href = URL.createObjectURL(
new Blob([JSON.stringify(window.localStorage.getItem("example"), null, 2)], {
type: "text/json"
}));
a.setAttribute("download", "examplefile.json");
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
一切都运转良好。当我使用文本编辑器打开创建的文件时,我得到以下输出:
"[{\"legs\":\"a\",\"color\":\"b\"}]"
多个在线验证器和我的浏览器确认 json 内容有效。
我的预期输出是:
[{"legs":"a","color":"b"}]
。我的问题是,在创建列表的预期输出时我错过了什么,还是这只是一个思维错误?
问题是你
stringify()
两次。当您将其存储在本地存储中时一次,然后当您创建 Blob
时再一次。
该问题有两种可能的解决方案:
创建 Blob 时删除
JSON.stringify()
调用,并已使用 window.localStorage.setItem("example", JSON.stringify(arr, null, 2))
将缩进的字符串存储在本地存储中
当您从本地存储检索字符串时,首先解析它,然后使用应用的缩进再次序列化它
const storedJson = window.localStorage.getItem("example");
const indentedJson = JSON.stringify(JSON.parse(storedJson), null, 2);
const blob = new Blob([indentedJson], { type: "text/json" });
a.href = URL.createObjectURL(blob);