简体   繁体   English

Javascript 遍历 JSON 文件

[英]Javascript iterating through JSON file

{
  "comments": [
    {
      "created_utc": 1622513325,
      "text": "gdhg sgf sddsfsd fdsf"
    },
    {
      "created_utc": 1622513188,
      "text": "sfdg sgf fdgfdg"
    }
   ]
}

How would you iterate over each object to see the text?您将如何遍历每个对象以查看文本?

Something like..?就像是..?

  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)
    }
  }

If you know the structure of your JSON will always be a comments object on the first level, containing a list of elements with created_utc and text , you can do as easy as the following code.如果您知道 JSON 的结构将始终是第一级的comments对象,其中包含具有created_utctext的元素列表,您可以像下面的代码一样简单。

You don't need to nest the cycle as you only want to iterate over one list, then read the items and directly access to the text field of each item.您不需要嵌套循环,因为您只想遍历一个列表,然后读取项目并直接访问每个项目的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); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM