Reputation: 690
First off, I am trying to parse JSON and I'm using a file locally.
When I run the following:
$.getJSON('/trivia_demos.json', function(data) {
alert("It worked!); });
The alert box comes up and I can confirm I am calling the right file locally. Console.log works as well. So far, so good.
I now want to pull several parts of the data and show them on the page. The JSFiddle is here, but the relevant code is the following:
$.getJSON('/trivia_demos.json', function(data) {
var items = []
$.each(data.reponse, function(item, i) {
items.push('<li id="' + i.order + '">' + i.question + ' - ' + i.answer + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('#example');});
In effect, I want the order, question, and answer appended to my div "#example". When I load the page, nothing happens though. In light of my first point, I believe I am screwing up the construction of the JQuery to target those three pieces of data and display them.
I believe something is missing between calling the json file and actually accessing the json object.
Also, in the trivia_demos.json file, the following json is present.
[{"id":1,"order":1,"question":"Who was the only American President to
learn English as a second language? ","answer1":"John Quincy Adams",
"answer2":"Martin van Buren","answer3":"William McKinley ",
"answer4":"Andrew Jackson","correcta":"Martin van Buren",
"published":"2014-11-04","url":"http://example.com/trivia_demos/1.json"}]
Upvotes: 0
Views: 96
Reputation: 2869
Based on jquery.getjson documentation it $each loop should work with just data parameter:
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Also, I tested your code without json part and it worked fine apart from i.answer
that I changed to i.answer1
also data.response
was changed to data
:
$.each(data, function (item, i) {
items.push('<li id="' + i.order + '">' + i.question + ' - ' + i.answer1 + '</li>');
});
Upvotes: 1
Reputation: 4125
Try something like this:
var json = '[{"id":1,"order":1,"question":"Who was the only American President to learn English as a second language? ","answer1":"John Quincy Adams","answer2":"Martin van Buren","answer3":"William McKinley ","answer4":"Andrew Jackson","correcta":"Martin van Buren","published":"2014-11-04","url":"http://example.com/trivia_demos/1.json"}]';
var obj = JSON.parse(json);
var content = '<ul>';
$(obj).each(function()
{
var li = '<li id="'+ this.order +'">' + this.question + ' - ' + i.answer + '</li>';
content += li;
});
content += '</ul>';
$('#example').html(content);
Upvotes: 1