I'm trying to create a javascript variable my_jason
from the contents of a JSON file "gunsList.json" (both are stored within the same folder on my machine).
I seem to be having the same issue that the OP had in this post, which was resolved when he corrected his flawed JSON file. Thinking I have the same issue, I ran my file through JSONLint (I'm assuming that's proper validation), and it came back clean.
Borrowing tips from this post, I tried using jQuery to get it done (note: I'm using jQuery successfully in other parts of the existing code), as follows:
var my_json;
$.getJSON('gunList.json', function(json) {
my_json = json;
});
When I try the method above (e.g., alert(my_json)
), my_json
is undefined
.
Admittedly, I know very little about AJAX, but I also tried:
var my_json = (function () {
var my_json = null;
$.ajax({
'async': false,
'global': false,
'url': 'gunsList.json',
'dataType': "json",
'success': function (data) {
my_json = data;
}
});
return my_json;
})();
In the case above, my_json
is null
.
All my code that references the array within "gunsList.json" when I paste it in as a variable in my js file runs fine, but as a fledgling programmer, I'd be really excited about getting it to work with JSON.