Jacinto
Jacinto

Reputation: 558

Working With JSON

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.

Upvotes: 1

Views: 8719

Answers (3)

jornare
jornare

Reputation: 2893

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

Upvotes: 5

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

For the JSON construct you have, a looping like below should be correct.

DEMO

$.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
    });
});

Upvotes: 0

Tuan
Tuan

Reputation: 5412

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.

Upvotes: 0

Related Questions