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

如何将指定JSON结构解析为可遍历的JavaScript对象?

解决JSON解析错误并遍历数据的方法

首先,你遇到的JSON.parse: unexpected character错误,大概率是因为传入JSON.parse()的字符串格式有问题,比如引号冲突、包含了非JSON内容(比如你提供的HTML标签),或者字符串没有正确转义。我们一步步来解决:

1. 确保JSON数据的正确性

你提供的JSON本身是有效的,但在JavaScript中使用时,要注意两种场景:

场景A:直接在JS代码中使用数据

如果是把这段JSON直接写在JS代码里,根本不需要用JSON.parse()——因为它本身就是一个合法的JavaScript对象字面量,直接赋值即可:

const itemsData = { 
  "FirstItem": { 
    "id": 1, 
    "type": "foo", 
    "colours": ["blue", "black", "green"], 
    "reviews": { 
      "positive": ["The best", "unbelievable", "Awesome"], 
      "negative": ["Sh*t", "Awful", "Dire", "Terrible", "Appalling"], 
      "neutral": ["OK", "Meh"] 
    } 
  }, 
  "SecondItem": { 
    "id": 2, 
    "type": "bar", 
    "colours": ["red", "white", "yellow"], 
    "reviews": { 
      "positive": ["Great", "Amazing", "Fantastic", "Perfect", "Uplifting"], 
      "negative": ["Terrible", "Shocking", "abysmal"], 
      "neutral": ["OK", "Standard", "Vanilla"] 
    } 
  } 
};

场景B:从字符串解析JSON

如果你的JSON是来自后端接口、本地存储等字符串形式,要确保字符串是正确转义的。比如用模板字符串(反引号)包裹,避免双引号冲突:

const jsonString = `{ 
  "FirstItem": { 
    "id": 1, 
    "type": "foo", 
    "colours": ["blue", "black", "green"], 
    "reviews": { 
      "positive": ["The best", "unbelievable", "Awesome"], 
      "negative": ["Sh*t", "Awful", "Dire", "Terrible", "Appalling"], 
      "neutral": ["OK", "Meh"] 
    } 
  }, 
  "SecondItem": { 
    "id": 2, 
    "type": "bar", 
    "colours": ["red", "white", "yellow"], 
    "reviews": { 
      "positive": ["Great", "Amazing", "Fantastic", "Perfect", "Uplifting"], 
      "negative": ["Terrible", "Shocking", "abysmal"], 
      "neutral": ["OK", "Standard", "Vanilla"] 
    } 
  } 
}`;
const itemsData = JSON.parse(jsonString);

⚠️ 注意:一定要确保jsonString里只有纯JSON内容,不要包含你提供的<h3>、<pre>这些HTML标签,否则肯定会解析失败。

2. 遍历并处理每个项

你的数据结构和C#里的字典类似,在JavaScript中可以用Object.keys()、Object.values()或Object.entries()来遍历:

方法1:只遍历项的值(忽略键名)

用Object.values()直接获取每个Item对象,适合不需要知道FirstItem/SecondItem这些键名的场景:

// 遍历每个Item
for (const item of Object.values(itemsData)) {
  console.log(`当前Item:ID=${item.id},类型=${item.type}`);
  
  // 遍历颜色列表
  console.log("颜色:");
  item.colours.forEach(colour => console.log(`- ${colour}`));
  
  // 遍历各类评论
  console.log("评论:");
  for (const [reviewType, comments] of Object.entries(item.reviews)) {
    console.log(`★ ${reviewType}:`);
    comments.forEach(comment => console.log(`  - ${comment}`));
  }
}

方法2:同时遍历键名和值

用Object.entries()可以同时拿到FirstItem这样的键名和对应的Item对象:

for (const [itemKey, item] of Object.entries(itemsData)) {
  console.log(`正在处理:${itemKey}`);
  // 后续处理逻辑和上面一致
  console.log(`ID=${item.id},类型=${item.type}`);
  // ... 处理颜色、评论
}

排查错误的小技巧

如果还是报错,可以用在线JSON校验工具把你的JSON字符串粘进去,检查是否有语法错误——比如遗漏逗号、引号不匹配等问题,这能快速定位问题所在。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:12:34