I am working with learning json right now and to get my feat wet so to speak I was wondering what would be the best way to get a file with json info and populate a site with it. The file would be something like this:
window.test =
{
"header1":
[
{ "title": "title1", "author": "author1"},
{ "title": "title2", "author": "author2"},
{ "title": "title3", "author": "author3"}
],
"header2":
[
{ "title": "title1", "author": "author1"},
{ "title": "title1", "author": "author2"},
{ "title": "title1", "author": "author3"}
]
};
Then would the code be something like this?
$(function() {
$.getJSON('jsonFile.js',function(data){
$.each(data, function(){
console.log(header1.title);
console.log(header2.title);
});
});
});
Again I am a newbie with JSON so any tutorials, suggestions, well anything to help me understand core concepts here would help.
window.test =
from the js file. The JSON code you can just have as a string and just eval()
it to create an object. I also found this peices of info very useful (more ASP.NET focused but get's the JSON idea over nicely): http://encosia.com/using-jquery-to-consume-aspnet-json-web-services - RemarkLima 2012-04-03 20:45
Your json:
{
"header1":
[
{ "title": "title1", "author": "author1"},
{ "title": "title2", "author": "author2"},
{ "title": "title3", "author": "author3"}
],
"header2":
[
{ "title": "title1", "author": "author1"},
{ "title": "title1", "author": "author2"},
{ "title": "title1", "author": "author3"}
]
}
Your code:
$(function() {
$.getJSON('jsonFile.js',function(data){
console.log(data.header1[0].title);
console.log(data.header2[0].title);
});
});
Optionally, do a each() over data.header1 and data.header2
As others have stated, you should remove the window.text
and the trailing semicolon. Then when you read the file directly like that, it will be encoded as text, so you need to translate it into JSON before iterating over it.
You can do var jsonData = JSON.parse(data));
to get a JSON object from the data parameter.
For the JSON construct you have, a looping like below should be correct.
$.each(test, function(key, val) {
console.log(key); //this will print the header
$.each(val, function(index, val1) {
console.log(val1.title + ' ' + val1.author); //this will print the header contents
});
});
window.test =
from the beginning) Did you encounter any errors? (You will, but trying this and explaining specific difficulties you encounter will make your question a lot easier to answer. - Michael Mior 2012-04-03 20:41