You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript生成JSON文件内容重复转义问题排查

问题原因及解决方法

你遇到的问题是双重JSON序列化导致的:

  • 你先对数组arr执行了JSON.stringify(arr),把它转成合法的JSON字符串存在localStorage里,此时localStorage中的内容已经是[{"legs":"a","color":"b"}]。
  • 但在exportA函数里,你又对从localStorage取出的这个字符串再次执行JSON.stringify,这会把整个字符串当成JSON的字符串值处理,所以给它包裹了一层双引号,同时转义了内部的双引号,最终得到"[{\"legs\":\"a\",\"color\":\"b\"}]"。

修正步骤

  1. 去掉exportA里多余的JSON.stringify,直接使用localStorage取出的字符串作为Blob的内容。
  2. 顺便修正代码里的语法错误:let arr[];应该改为let arr = [];,否则会触发语法报错。

修正后的完整代码:

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(
    // 去掉多余的JSON.stringify,直接使用localStorage取出的内容
    new Blob([window.localStorage.getItem("example")], {
      type: "text/json"
    })
  );
  a.setAttribute("download", "examplefile.json");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

内容的提问来源于stack exchange,提问作者Reporter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:27:06