Question

I have a json object that i created using obj = JSON.parse(data). "data" was recieved from a webserver. I know the object is correct because i can print single variables from it into a div or my list.

This is what is the json object is created from:

[{"name":"Staurikosaurus","group":"Saurischia","diet":"Carnivore","period":"Triassic"},{"name":"Diplodocus","group":"Saurischia","diet":"Herbivore","period":"Jurassic"},{"name":"Stegosaurus","group":"Ornithischia","diet":"Herbivore","period":"Jurassic"},{"name":"Tyrannosaurus","group":"Saurischia","diet":"Carnivore","period":"Cretaceous"}]

Literally all i want to do is put this into a to show up on a web page.

My current code:

 function getJson(){$.get(MY URL, function(data) {
            // String
            //console.dir(data);

            // Parse JSON
            var obj = JSON.parse(data);

            // JSON object
            //console.dir(obj);
            $('#myList').html("<li>"+obj[0].period+"</li><li>"+obj[2].period+"</li>");
            //$('#myList').html("<li>obj[2].period</li>");
        });

    }

This successfully prints out the list with Triassic then Jurrasic.

I would prefer to do this in Jquery but javascript is okay.

Thank You.

Was it helpful?

Solution

You are not iterating through the list, just printing out the 0-th and 2nd element in the array. Try:

function getJson(){$.get(MY URL, function(data) {
        // String
        //console.dir(data);

        // Parse JSON
        var obj = JSON.parse(data);

        // JSON object
        //console.dir(obj);
        var inner = '';
        for(i=0; i < obj.length; i++) {
             inner += "<li>"+obj[i].period+"</li>";
        }
        $('#myList').html(inner);
    });

}

I'm sure there's a cleaner way using jQuery but that should work

OTHER TIPS

If you're want to use the jQuery syntax, process like this:

var listElement = '';

$.each(obj, function(index, value) {
    listElement += '<li>' + data[obj].period + '</li>';
})

$('#myList').html(listElement);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top