遍历json文件的javascript

aiqt4smr  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(291)
{
  "comments": [
    {
      "created_utc": 1622513325,
      "text": "gdhg sgf sddsfsd fdsf"
    },
    {
      "created_utc": 1622513188,
      "text": "sfdg sgf fdgfdg"
    }
   ]
}

如何迭代每个对象以查看文本?
像。。?

let data = fs.readFileSync(path.resolve(__dirname, 'comments.json'));
  let comments = JSON.parse(data);
  for(var i in comments){
    for(var j in i) {
      console.log("? " + j.text)
    }
  }
pcww981p

pcww981p1#

如果您知道json的结构将始终是 comments 对象,包含具有 created_utctext ,您可以像下面的代码一样简单。
您不需要嵌套循环,因为您只想迭代一个列表,然后读取项目并直接访问 text 每个项目的字段。

var jsonString = `{
  "comments": [
    {
      "created_utc": 1622513325,
      "text": "gdhg sgf sddsfsd fdsf"
    },
    {
      "created_utc": 1622513188,
      "text": "sfdg sgf fdgfdg"
    }
   ]
}`;

let comments = JSON.parse(jsonString).comments;

comments.forEach(comment => {
  console.log(comment.text);
});

相关问题