【问题标题】:Accessing json objects within objects with Jade and express使用 Jade 和 express 访问对象内的 json 对象
【发布时间】:2013-04-19 00:33:13
【问题描述】:

我现在正在拔头发。我似乎无法弄清楚如何使用 Jade 访问以下 json 对象中的“媒体”内容。

   {
      "summary":"Jose Mourinho names his Real Madrid side to face Borussia Dortmund in the Champions League semi-final 24 hours early.",
      "type":"STY",
      "lastUpdated":"2013-04-23T16:31:39+00:00",
      "firstCreated":"2013-04-23T16:31:39+00:00",
      "hasShortForm":true,
      "media":{
         "images":{
            "index":{
               "67193384":{
                  "height":261,
                  "width":464,
                  "href":"http://thesun.co.uk/media/images/67193000/jpg/_67193384_67193383.jpg",
                  "altText":"Jose Mourinho"
               }
            }
         }
      },
   },

我可以访问摘要、类型、更新等。但我不知道如何访问 media.images.index.67193384 中的图像元数据

for item in results
    p #{item.summary}
    p #{item.lastUpdated}
    p #{item.media[0]} // ???

有人可以帮我弄清楚吗?我从未尝试访问对象内对象内的对象数据。此外,images.index 中的 67193384 对象是唯一的,并且会总是不同 从结果到结果。

谢谢!

【问题讨论】:

  • 您在制作 JSON 吗?它看起来不正确。图片不是数组。此外,使用“67193384”作为键也无济于事。

标签: javascript json node.js express pug


【解决方案1】:
for item in results
    p= item.summary
    p= item.lastUpdated
    - for (var key in item.media.images) {break;}
    p= item.images.index[key].height

for 循环是used to get your key

【讨论】:

  • 我似乎收到以下错误:Cannot read property 'index' of undefined。这与@robertklep 的解决方案不同:/
  • 我们是否可以检查该数据是否存在,以防特定项目丢失?
  • - console.log(dataToCheck) ?
【解决方案2】:

有点破解,但它有效:

- if (item.media && item.media.images)
  p #{item.media.images.index[Object.keys(item.media.images.index)[0]].height}

【讨论】:

  • 我似乎收到了以下错误Cannot read property 'images' of undefined。 ://
  • 我们是否可以检查该数据是否存在,以防特定项目丢失?
  • 在渲染其值之前,我添加了一个检查以查看 item.mediaitem.media.images 是否确实存在。
  • 不错!这就是我需要的!干杯哥们!
猜你喜欢
  • 2013-08-03
  • 2016-05-02
  • 2013-04-28
  • 2016-04-07
  • 2017-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多