如何在JSON中访问数组中的命名对象?

时间:2014-08-10 23:30:59

标签: json pug harp

我正在使用Jade模板处理Harp项目。我的_data.json填充了内容,但我无法以我认为的方式访问它。给定这个JSON结构:

{
"mountain-residence": {
    "slug": "mountain-residence",
    "title": "Mountain Residence",
    "lead": "A southeast facing home...",
    "thumb": "exterior/entry",
    "sections": [
      {
        "exterior": {
          "slug": "exterior",
          "title": "Exterior Photos",
          "lead": "Embracing an entry...",
          "thumb": "terrace",
          "photos": [
            {
              "slug": "southeast",
              "alt": "Mountain Room Overlook",
              "caption": "Porch, deck and spa terrace"
            },
            {
              "slug": "terrace",
              "alt": "Southeast Terrace",
              "caption": "Spa deck and landscape terrace"
            },
            {
              "slug": "entry",
              "alt": "Entry Courtyard",
              "caption": "Entry court and pergola"
            },
            {
              "slug": "porch",
              "alt": "Entry Porch",
              "caption": "Timber entry shelter"
            }
          ]
        }
      },
      {
        "interior": {
          "slug": "interior",
          "title": "Interior Photos",
          "lead": "The interior spaces...",
          "thumb": "mountain-room2",
          "photos": [
            {
              "slug": "mountain-room2",
              "caption": "Entry opening to the Mountain Room"
            },
            {
              "slug": "dining",
              "caption": "Dining Room into Mountain Room"
            },
            {
              "slug": "cellar1",
              "caption": "Wine Cellar and Tasting Room"
            },
            {
              "slug": "den",
              "caption": "Den and Family Hearth"
            }
          ]
        }
      },
      {
        "design-sketches": {
          "slug": "design-sketches",
          "title": "Design Sketches",
          "lead": "A careful site...",
          "thumb": "shower",
          "photos": [
            {
              "slug": "schematic",
              "caption": "Exterior Elevation Study"
            },
            {
              "slug": "elevation",
              "caption": "Elevation Color Studies"
            },
            {
              "slug": "shower",
              "caption": "Outdoor stone shower"
            }
          ]
        }
      }
    ]
  }
}

我无法弄清楚如何访问数组中的命名对象,例如mountain-residence.sections.exterior.title(“外部照片”)。尝试mountain-residence.sections['exterior'].title也不起作用。我可以使用mountain-residence.sections[0].title访问相同的属性,并且我的JSON似乎有效,但我需要使用其名称调用该对象...有没有办法做到这一点?

例如,"mountain-residence"填充页面,我的一般想法是让"sections"中的每个对象填充自己的子页面,这就是为什么我希望能够通过它来调用它通过我的JSON命名。

1 个答案:

答案 0 :(得分:0)

如评论中所述,sections是一个数组,因此只有索引表示法才有效。如果你想通过该部分的名称来获取它,它必须是本地的对象,或者通过预处理你编写的代码转换为对象。