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

JavaScript遍历JSON文件提取comments数组text属性的实现方法

问题排查&修正方案

原代码错误点

  • 变量命名混淆:JSON.parse返回的是整个JSON根对象,你将其命名为comments,但实际存储评论数组的是根对象下的comments属性,二者完全不是一个东西
  • for...in遍历对象拿到的是键名而非值:第一层循环里的i是字符串类型的键"comments",不是评论数组
  • 第二层遍历直接遍历字符串i,拿到的j是字符串的字符索引,不可能取到text属性

正确实现代码

const fs = require('fs')
const path = require('path')

// 读取&解析JSON逻辑可以保留
const data = fs.readFileSync(path.resolve(__dirname, 'comments.json'));
const jsonResult = JSON.parse(data);
// 先拿到评论数组
const commentArr = jsonResult.comments;

// 最简洁的遍历方式:forEach
commentArr.forEach(item => {
  console.log(item.text)
})

// 如果需要支持循环中break/continue,用for...of
// for (const item of commentArr) {
//   console.log(item.text)
// }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 19:57:04