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

时间:2015-06-30 12:31:06

标签: javascript jquery json

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

var content = $.getJSON("website-contents.json");
var place = content["cards"];

当我在Chrome开发工具中调用内容变量时,它会返回我的主对象,但是当我调用'place'变量时,它只返回undefined。我也尝试了var place = content.cardsvar 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"
      }
    }
  }
}

2 个答案:

答案 0 :(得分:7)

getJSON()asynchronous。您需要将成功处理程序传递给它,并解析数据:

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

答案 1 :(得分:1)

试试这个......

var place; 
var content = $.getJSON("website-contents.json", getcards);
function  getcards(content) {
    place = JSON.parseJSON(content).cards;
}