Reputation: 232
Just getting a simple .json file and parsing it, or not. Both fail anyway. I tried the solutions from other threads and none worked. console.log() shows an object, but I cant use it. I tried changing the json a few different ways but that didnt work. This is the .json file:
[ {
"name": "Alabama",
"abbreviation": "AL"
},
{
"name": "Alaska",
"abbreviation": "AK"
},
{
"name": "American Samoa",
"abbreviation": "AS"
},
{
"name": "Arizona",
"abbreviation": "AZ"
}]
It looks ok to me. So I added this function to use it:
function fillStates(){
var obj = $.get('states.json');
console.log(obj);
var states = JSON.parse(obj);
//console.log(states);
}
Upvotes: 0
Views: 885
Reputation: 12508
Let's backup and examine what $.get()
is. This method is simply a shorthand method for:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
See the reference documentation. Now let's jump over to the $.ajax
documentation to understand how jQuery parses the return value:
Per the documentation:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, =[TIMESTAMP], to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
"json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "=[TIMESTAMP]", to the URL unless the cache option is set to true.
"text": A plain text string.
multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml". Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
So to sum things up, jQuery will interpret the response using it's intelligent guess method since you didn't specify a return data type. The data type will be inferred as JSON
and will be parsed to a JavaScript object. For this reason, you shouldn't ever need to do JSON.parse(...)
on the returned data when using a jQuery based ajax method such as $.get
, $.post
, $.ajax
, $.load
(the data method, not the event handling suite method) or $.getJSON
.
Continuing on, AJAX
stands for asynchronous JavaScript and XML. The asynchronous part is key here. The request is operated out of band while JavaScript execution continues on the page starting at the next line. In your case obj
will be a $.promise
, not the result. Parsing this using JSON.parse
will result in an error.
You have two options from here:
.done()
.success
callback function to execute upon successful completion of the ajax
request.Both examples are outliend below:
Using .done()
:
var obj;
function fillStates() {
$.get('states.json').done(function (data) {
obj = data;
console.log(obj);
});
}
Using a success
callback:
var obj;
function fillStates() {
$.get('states.json', function (data) {
obj = data;
console.log(obj);
});
}
Upvotes: 1
Reputation: 6770
I guess you are misunderstanding jQuery $.get()
method. It will return a Promise object and not the data you want:
As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.
That's why you are giving a [object Object]
to JSON.parse()
function.
You must use a success callback:
function fillStates(){
var obj = $.get('states.json', function(data) {
// It will be executed in case of sucess
console.log(data);
});
}
Upvotes: 2
Reputation: 6457
Usage of $.get
is not correct since it is an async execution. This should work:
$.get( "states.json", function( obj ) {
var states = JSON.parse(obj);
});
Upvotes: 1
Reputation: 36609
Before JSON.parse(), just check typeOf obj==='object'
. If true then there is no need to parse as variable is already an object.
Upvotes: 0