Sullan
Sullan

Reputation: 1157

Getting values from 2 sets of data from JSON file

I am parsing data from a json file and converting to a HTML table, this is done, but I have 2 sets of data in the JSON file. The second one is to get the direct value. I dunno where i am doing wrong, is the JSON format or the the way i am trying to get the values. Can anybody guide me on how to achieve this ??

//Json File format

{ "posts": [ { "title":"12", "answer":"55.5" }, { "title":"123", "answer":"66.6" },] "author": [ { "book":"12", "date":"55.5" },] }

// Script

$.getJSON("wc.json",function(data)
{
alert(author.book);
alert(author.date);
$.each(data.posts, function(i,data)
{
var faqs =
"<tr><td>"+data.title+"</td><td>"+data.answer+"</td></tr>";
$(faqs).appendTo("#faq tbody");
});
}
);
return false;
});

Upvotes: 0

Views: 403

Answers (2)

Theo
Theo

Reputation: 1

I think you need to rename the array value in the nested each, then call the property against that, like so:

$.each(data.posts, function(i,post){
  var faqs = "<tr><td>"+post.title+"</td><td>"+post.answer+"</td></tr>";
  $(faqs).appendTo("#faq tbody");
});

hth Theo

Upvotes: 0

Jeff the Bear
Jeff the Bear

Reputation: 5653

The JSON format you have has syntactic errors. Try this:

HTML:

<table id="faq"><tbody></tbody></table>

Script:

var data = { 
"posts": [ { "title":"12", "answer":"55.5" },
           { "title":"123", "answer":"66.6" }],
"author": [ {"book":"12", "date":"55.5" }] }


$.each(data.posts, function(i,data)
{
  var faqs =
  "<tr><td>"+data.title+"</td><td>"+data.answer+"</td></tr>";
  $(faqs).appendTo("#faq tbody");
});

BTW, the author key is set to an array which needs to be accessed in an array: author[0].book in the alerts.

Upvotes: 2

Related Questions