Reputation: 1695
I have a very basic JSON extract seen here.
[
{ first: "bob", last: "jones", },
{ first: "josh", last: "smith", }
]
I am trying to parse this into HTML using $.getJSON
.
I have never used this jquery function before and am having issues. My guess is I am missing something in the info div.
I currently have JSON URL in this example but my live code has the actual URL.
Thanks for any guidance, here is my code:
$.getJSON('JSON URL', 'limit=5', processNames);
function processNames(data) {
var infoHTML='';
$.each(data, function(name) {
infoHTML += 'First: ' + name.first;
infoHTML += 'Last: ' + name.last;
});
$('#info').html(infoHTML);
}
<div id="info"></div>
Upvotes: 0
Views: 139
Reputation: 645
In JSON, keys must be in double quotes (so must strings). Single quotes aren't allowed, and quotes are required.
When using JSON you must make sure that it is a valid one.
it is very easy to miss a comma,quote or mismatch brackets. for that purpose I recommend using JSON validator
When checking the JSON object in your question I found that it's invalid for two reasons:
When getting an answer from the server I recomend to check and see if this is the answer you expected it to be. for example, before $.each(data, function(name) you can do the following
alert(JSON.stringify(data,));
This will show you the string received from the server.
Generally I recomend using $.ajax instead of $.getJSON because you have more control over the response from the server, you can decide if you want it cached, asynchronous call and so on.
you can see the jQuery Ajax API here
Hoped my answer helped you.
Upvotes: 0
Reputation: 39456
Your JSON is invalid. You are missing quotes around the field names. Try something like this:
[
{ "first": "Bob", "last": "Jones" },
{ "first": "Josh", "last": "Smith" }
]
Upvotes: 3