I am trying to parse this JSON string:
{ "RESULTS": [ { "name": "Thessaloniki GR", "type": "Sailing", "l": "/sailing-weather/beach:Porto%20Carras%20Marina 45904" }, { "name": "Thessaloniki, Greece", "type": "city", "c": "GR", "zmw": "00000.1.16622", "tz": "Europe/Athens", "tzs": "EET", "l": "/q/zmw:00000.1.16622" } ] }
which is retrieved from here
This is my snippet:
$(document).ready(function () {
$("#w11").autocomplete({
source: function (a, b) {
$.ajax({
url: "http://autocomplete.wunderground.com/aq",
dataType: "jsonp",
data: {
format: "jsonp",
query: a.term
},
success: function (a) {
for (i in data.RESULTS) {
console.log(data.RESULTS);
}
}
})
}
});
});
Which gives me an error Uncaught SyntaxError: Unexpected token : on the first line which is { "RESULTS": [
How can I parse the JSON Results?
You’ve told jQuery to expect JSON-P, not JSON:
…but the result is JSON. JSON-P and JSON are fundamentally different things. Here’s an example JSON response:
Here’s what a JSON-P response might look like:
or
If
http://autocomplete.wunderground.com/ais not on the same origin as the document your code is running in, you won’t be able to retrieve JSON from it via ajax because of the Same Origin Policy (unless the server in question supports CORS, allows your origin for the request, and the browser the user has also supports CORS). Which I suspect is why you tried to use JSON-P, which works cross-origin. The thing is, though, that the server has to support JSON-P as well. Despite theformat=jsonpin the URL, the server is not responding with JSON-P, but with JSON.In the comments, you linked to their docs for that API, which show that they do support JSON-P for it, just using a non-standard argument name in the URL (
cbinstead of the much more commoncallback).So this should work (I’ve also fixed the issues with the code I mentioned in my comment on the question):
And in fact it does work: Live Example | Source
The
jsonpargument tells jQuery what URL parameter to use to define the name of the JSON-P callback. The default is the standardcallbackbut that API uses a non-standard argument.