2

I would like to store a part of my main JSON object in a variable so that I can loop through it (For example, store 'cards' so I can loop through Govenors, Courses, and Teachers to get the 'title' and 'href' before creating an element with them). Currently I am doing:

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

When I call the contents variable in Chrome Dev Tools,it returns my main object but when I call the 'place' variable, it just returns undefined. I have also tried var place = content.cards and var place = content[0] but nothing seems to work. Here is my JSON (Apologies for the length)

{
  "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"
      }
    }
  }
}
Alex Shaw
  • 169
  • 2
  • 10

2 Answers2

7

getJSON() is asynchronous. You need to pass it a success handler, and parse the data out:

var place, 
    content = $.getJSON("website-contents.json", function(data) {
    place = data.cards;
});
arthurakay
  • 5,261
  • 7
  • 37
  • 57
1

try this out ...

var place; 
var content = $.getJSON("website-contents.json", getcards);
function  getcards(content) {
    place = JSON.parseJSON(content).cards;
}
kavetiraviteja
  • 1,717
  • 10
  • 30