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

解析JSON后对象键值为undefined是什么原因?如何正确解析访问?

问题原因
  • 错误调用了JSON.stringify():你的MY_JSON_FILE本身已经是符合格式的JSON字符串,不需要再做序列化处理。JSON.stringify()会把原JSON字符串再次转义,后续JSON.parse执行后得到的结果还是字符串类型,而非你期望的JS对象,自然无法读取对应属性。
  • 原JSON字符串末尾携带了\x00空字符,会干扰JSON解析逻辑。
修复方案

去掉多余的JSON.stringify步骤,同时清理字符串末尾的空字符即可,修改后代码如下:

const MY_JSON_FILE = "{ \"version\": \"1.0\", \"result\": 4, \"id\": \"1\" }\x00"
// 清理空字符后直接生成blob,不需要额外序列化
const blob = new Blob([MY_JSON_FILE.trimEnd()], {type:"application/json"});
const fr = new FileReader();
var res;
fr.onload = () => {
  console.log('done', fr.readyState);
  console.log('reader result: ', fr.result);
  // 直接解析即可得到JS对象
  res = JSON.parse(fr.result);
  console.log(Object.keys(res));
  console.log('parsed: ', res);
  console.log(res.id); // 输出 1
  console.log(res.result); // 输出 4
  console.log(res.version); // 输出 1.0
}
fr.readAsText(blob);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:27:03