将JSON对象的一部分存储在javascript变量中

Ale*_*haw 2 javascript jquery json

我想将一个主JSON对象的一部分存储在一个变量中,以便我可以遍历它(例如,存储'cards',这样我就可以遍历Govenors,Courses和Teachers来获得'title'和'href '在用它们创建元素之前).目前我在做:

var content = $.getJSON("website-contents.json");
var place = content["cards"];
Run Code Online (Sandbox Code Playgroud)

当我在Chrome开发工具中调用内容变量时,它会返回我的主对象,但是当我调用'place'变量时,它只返回undefined.我也试过var place = content.cards,var place = content[0]但似乎没有任何工作.这是我的JSON(道歉长度)

{
  "accordian" : {
    "faqs" : {
      "head" : {
        "answer" : "Simon Firth",
        "question" : "Whos the head?"
      },
      "location" : {
        "answer" : "Wylye Bulding, Wiltshire College",
        "question" : "Where are we based?"
      }
    }
  },
  "article" : {
    "new-site" : {
      "Title" : "Launch of new website!",
      "author" : "Alex Shaw",
      "content" : "We now have a new website due to the amazing computing students!",
      "hashbang" : "newSite"
    },
    "test" : {
      "author" : "A Shaw",
      "content" : "This is a test article",
      "hashbang" : "test",
      "title" : "Test Article"
    }
  },
  "cards" : {
    "govenors":{
      "title":"Govenors",
      "href":"#govenors",
      "abanks":{
        "name":"Alec Banks"
      },
      "nowen":{
        "name":"Neil Owen"
      }
    },
    "courses" : {
      "title":"Courses",
      "href":"#courses",
      "Art" : {
        "teacher" : "Mrs Bellars",
        "title" : "Art"
      },
      "Biology" : {
        "teacher" : "Mrs Miller",
        "title" : "Biology"
      },
      "Computing" : {
        "teacher" : "Mr Chambers",
        "title" : "Computing"
      },
      "Further Maths" : {
        "teacher" : "Mr Grimsley",
        "title" : "Further Maths"
      },
      "Maths" : {
        "teacher" : "Mr Grimsley",
        "title" : "Maths"
      }
    },
    "teachers" : {
      "title":"Teachers",
      "href":"#teachers",
      "cchambers" : {
        "email" : "email1",
        "name" : "Craig Chambers"
      },
      "kgrimsley" : {
        "email" : "email2",
        "name" : "Kevin Grimsley"
      },
      "sfirth" : {
        "email" : "email3",
        "name" : "Simon Firth"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

art*_*kay 7

getJSON()是异步的.您需要将成功处理程序传递给它,并解析数据:

var place, 
    content = $.getJSON("website-contents.json", function(data) {
    place = data.cards;
});
Run Code Online (Sandbox Code Playgroud)