0

The idea is to take a JSON array, loop through each of the entries for planets and output them to an unordered list, with one entry per li. All works well in this instance.

I have successfully written a method to output nested JSON when the JavaScript file contains the JSON array and the code below it, but I am having serious trouble identifying a method to retrieve the same data from an external .json file, using AJAX.

Here is the working local version.

<ul id="object-list"></ul>
$(document).ready( function() {
    var sol_sys = [];
    sol_sys = {
        "stars": [
            { "name": "Sun", "object": "Star", "url": "stars/sun" }
        ],
        "planets": [
            { "name": "Mercury", "object": "Planet", "parent": "Sun", "url": "planets/mercury" },
            { "name": "Venus", "object": "Planet", "parent": "Sun", "url": "planets/venus" },
            { "name": "Earth", "object": "Planet", "parent": "Sun", "url": "planets/earth" },
            { "name": "Mars", "object": "Planet", "parent": "Sun", "url": "planets/mars" },
            { "name": "Ceres", "object": "Dwarf Planet", "parent": "Sun", "url": "planets/ceres" },
            { "name": "Jupiter", "object": "Planet", "parent": "Sun", "url": "planets/jupiter" },
            { "name": "Saturn", "object": "Planet", "parent": "Sun", "url": "planets/saturn" },
            { "name": "Uranus", "object": "Planet", "parent": "Sun", "url": "planets/uranus" },
            { "name": "Neptune", "object": "Planet", "parent": "Sun", "url": "planets/neptune" },
            { "name": "Pluto", "object": "Dwarf Planet", "parent": "Sun", "url": "planets/pluto" },
            { "name": "Eris", "object": "Dwarf Planet", "parent": "Sun", "url": "planets/eris" }
        ],
        "moons": [
            { "name": "Luna", "object": "Moon", "parent": "Earth", "url": "moons/luna" },
            { "name": "Callisto", "object": "Moon", "parent": "Jupiter", "url": "moons/callisto" },
            { "name": "Ganymede", "object": "Moon", "parent": "Jupiter", "url": "moons/ganymede" },
            { "name": "Io", "object": "Moon", "parent": "Jupiter", "url": "moons/io" },
            { "name": "Europa", "object": "Moon", "parent": "Jupiter", "url": "moons/europa" },
            { "name": "Enceladus", "object": "Moon", "parent": "Saturn", "url": "moons/enceladus" },
            { "name": "Titan", "object": "Moon", "parent": "Saturn", "url": "moons/titan" },
            { "name": "Miranda", "object": "Moon", "parent": "Uranus", "url": "moons/miranda" },
            { "name": "Triton", "object": "Moon", "parent": "Neptune", "url": "moons/triton" },
            { "name": "Charon", "object": "Moon", "parent": "Pluto", "url": "moons/charon" }
        ]
    }

    var x = [];
    $.each(sol_sys.planets, function(index) {
        x += '<li><a href="' + sol_sys.planets[index].url + '" title="' + sol_sys.planets[index].name + '" target="_blank">' + sol_sys.planets[index].name + '</a></li>';
    });
    $('#object-list').append(x);
});

However, I have spent the past two days trying to figure out the method to achieve this, with the JSON kept separate in a separate .json file.

Here is an example of one method I have tried:

$(document).ready( function() {
    var sol_sys = $.getJSON('assets/data.json');
    var x = [];

    $.each(sol_sys.planets, function(index) {
        x += '<li><a href="' + sol_sys.planets[index].url + '" title="' + sol_sys.planets[index].name + '" target="_blank">' + sol_sys.planets[index].name + '</a></li>';
    });
    $('#object-list').append(x);
});

This code successfully fetches the data as can be seen in the console, but it also spits out this error message: Uncaught TypeError: Cannot read property 'length' of undefined

I am thinking that there is something obvious that I have completely missed. I have also tried the method demonstrated here, with exactly the same outcome.

Can anybody point me in the right direction?

Thanks!

14
  • Hi @DmitryS., I'm not sure what you mean exactly? Commented Feb 15, 2019 at 19:27
  • You described the above code fetches the data successfully using ajax as you see in the console. Can you show that console result? It seems sol_sys.planets is not an array. Commented Feb 15, 2019 at 19:35
  • @DmitryS. I think I mixed up some testing that I was doing in the console, pasting the var sol_sys line in there directly. I have tried so many things, I lost track. Sorry about that. It definitely does not work. Commented Feb 15, 2019 at 19:38
  • So, what the result do you get using $.getJSON('assets/data.json')? Can you provide a result of console.log(sol_sys) after you fetch data? Commented Feb 15, 2019 at 19:40
  • Possible duplicate of jQuery getJSON save result into variable Commented Feb 15, 2019 at 19:43

2 Answers 2

2

$.getJSON is an async call - so you need to use the callback function to access the returned data:

$.getJSON('assets/data.json', function(sol_sys) {
    var x = [];

    $.each(sol_sys.planets, function(index) {
        x += '<li><a href="' + sol_sys.planets[index].url + '" title="' + sol_sys.planets[index].name + '" target="_blank">' + sol_sys.planets[index].name + '</a></li>';
    });
    $('#object-list').append(x);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Hello, thank you for your answer. I copied your code over directly, and it still doesn't appear to be working.
Turns out the JSON was incorrectly formatted. Your solution now works too. My bad. Thank you. :)
1

Hi you can do it this way:

your ajax:

function getList() {
   return $.ajax({
        type: "GET",
        url: "YourUrl"
    })

}

call it like this:

    getList().done(function(response){
    var data=JSON.parse(response);
    if (data != null) {
    jQuery.each(data, function(index, value){
//use an id in your ul in order to append some items
    $("#yourUl id").append('<li><a href=' + value.url+ '>' + value.name+ '</a></li>');
                                                    });
        }

})

Or

$.getJSON( 'assets/data.json').done(function(response) {
    var data=JSON.parse(response);
    if (data != null) {
    jQuery.each(data, function(index, value){
    //use an id in your ul in order to append some items
    $("#yourUl id").append('<li><a href=' + value.url+ '>' + value.name+ '</a></li>');
});
}
})

Edit: append the elements like this:

        $.getJSON( 'data.json').done(function(response) {
    jQuery.each(response, function(index, value){
    $("#planetList").append('<li>'+index+'</li>');
     jQuery.each(value, function(index2, value2){
    $("#planetList").append('<ul><li><a href=' +value2.url+ '>' +value2.name+ '</a></li>')
    console.log(value2);
     })
         $("#planetList").append('<ul>');
    })
})

Hope it helps

14 Comments

@DylRicho can you log the response and post a picture of that ?
@DylRicho i will try to do this on my pc and give you an update
@DylRicho i have edited the post check is the answer helps
@DylRicho the json you get where it comes from ? is an array generated from some database or is static array in some js file? cause i use your json and it create the list imgur.com/a/iG9xw1Q
@dyl i just added a picture from the result i get
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.