1

I am very new to this, trying to follow http://javascriptissexy.com/how-to-learn-javascript-properly/ by making a quiz, any additional advice is welcome. I put the JSON file at the bottom of js as comment.

http://jsfiddle.net/Atlas_/Mgyc5/

Supposed to be the holy grail ? :I

var theQuiz;
$.getJSON("package.json", function (json) {
    theQuiz = json;
});
Atlas
  • 107
  • 2
  • 8

3 Answers3

2

Thanks guys, i figured it out by checking and rechecking the dev console, but mostly staring at the monitor in disbelief. I actually need help now to get it to work with a server tried few including a local one and no luck.

Valuable Lesson

$.getJSON("package.json", /*loads, if in the same folder*/ function (json) {
theQuiz = json.quiz; // Had to make sure to pick out the array because JSON put it into an extra object
console.log(theQuiz); // object Array
console.log(json);  // object Object
console.log(theQuiz[0].question); // Works! "How many times your heart beats in a day?(choose the closest)"
// but it's not working because js doesn't wait for JSON to load and it starts using the variables that doesn't exist yet
});

Solution

$.ajax({
dataType: "json",
async: false, // Makes sure to wait for load
url: "package.json", //  https://www.dropbox.com/s/fmw63i4v7dtnx6t/package.json
'success': function (json) {
    theQuiz = json.quiz;
    console.log(json);  // object Object
    console.log(theQuiz); // object Array
    // Finishes loading before js starts using it, and works as intended
}
});
Atlas
  • 107
  • 2
  • 8
1

try something like this

JSON FILE[json.js]

 var country = {name:"india",code:"IND"};

HTML FILE

// adding file in script
<script src="json.js"></script>

//using json in script
<script>
  country.name // will give india
</script>
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
-1

Using getJSON you can load JSON-encoded data from the server using a GET HTTP request. you cannot load a local file with that function. You can load local file but that is not very easy. Check the below link.

Local file access with javascript

Also please check

Trying to load local JSON file to show data in a html page using JQuery

Community
  • 1
  • 1
A Paul
  • 8,113
  • 3
  • 31
  • 61
  • 1
    if package.json is in the same folder as the html file this is a valid request(relative path) – Exlord Jan 01 '14 at 05:30
  • @Exlord - If you check http://api.jquery.com/jQuery.getJSON/. JQuery document tation says "JSON-encoded data from the server". This does not at all talk about the relative path. Let me know if I am missing something. – A Paul Jan 01 '14 at 05:32
  • ok you could be right i just assumed that he is running the file on a server if he is opening the html file directly then yes getJson dosn't even run – Exlord Jan 01 '14 at 05:55