Reputation: 40202
I'm using a book API that returns the following
var _OLBookInfo = {
"ISBN:234234234234234": {
"bib_key": "ISBN:234234234234234",
"preview": "noview",
"preview_url": "http://openlibrary.org/b/adsfasdfa",
"info_url": "http://openlibrary.org/b/adsfasdf",
"details": {
"publishers": [
"W. H. sdafasdfasdf"
]
}
};
How can I parse this with jQuery using the callback parameter of $.get()
Specifally, how do I get easy access to details -> publishers
Update
$.post("/Home/LookupBook", { query: lookuptxt.val() },
function (data) {
alert(data); //returns proper json data
alert(data.details.publishers[0]); // get erro saying details.publishers[0] is null
},
"json");
Upvotes: 1
Views: 720
Reputation: 28130
Don't confuse JSON with JavaScript. What you provide in that example is a JavaScript statement, specifically an assignment statement. _OLBookInfo gets as its value that big hash of data.
Short answer: To make your example valid JSON, get rid of the var _OLBookInfo =
part (and the trailing semicolon). JSON is just the object literal or array literal on its own. It's an expression, not a statement.
So the problem isn't with your JavaScript or jQuery, it's with the API. Whoever's API you're using mislead you if they said it returns JSON. If it's your own API, you can easily fix it to be valid JSON.
Upvotes: 1
Reputation: 10147
Uhhh, JSON doesn't need to be parsed in JavaScript. That's kinda the point in returning data in that format from the server.
Upvotes: 1
Reputation: 43619
You don't have to parse a JSON string in JS. Simply see $.getJSON() method of jQuery.
http://docs.jquery.com/Ajax/jQuery.getJSON
Example:
$.getJSON( url, data, function(response){
alert(response['ISBN:234234234234234'].details.publishers[0]);
} );
I just saw that your call doesn't only return the JSON, but instead returns the JS file.
What you can do is to eval()
the data returned from $.get()
$.get( url, data, funcCallback);
function funcCallback(data, status){
eval(data);
alert(_OLBookInfo['ISBN:234234234234234'].details.publisher[0]);
}
By the way, your JSON string is invalid. It has one missing curly brace at the back.
You can also try $.getScript():
http://docs.jquery.com/Ajax/jQuery.getScript
Upvotes: 2