0

I am currently trying to parse a random JSON file online, you can try the link and look at it for yourself. No matter what I look for, I always get 'undefined' when accessing the data. I just want to get some sort of output from the json. For example, how can I get the list of names ('nm') in the file? No matter what I do, it always gives me undefined.

    $.ajax(
    {
        type: 'GET',
        url: 'http://mysafeinfo.com/api/data?list=englishmonarchs&format=json',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function(r)
        {
            alert(r.example);
        }
    });
  • No matter what I put in the alert statement, it gives me undefined – user3311987 May 30 '15 at 22:48
  • 1
    I recommend to read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Array_object and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects to learn the basics about arrays and objects in JavaScript. – Felix Kling May 30 '15 at 22:53

2 Answers2

1

The data fetched from that API is an array of objects like this.

[{
  nm: "Edward the Elder",
  cty: "GB",
  hse: "House of Wessex",
  yrs: "899-925"
}, {
  nm: "Athelstan",
  cty: "GB",
  hse: "House of Wessex",
  yrs: "925-940"
}]

One of the ways to iterate over the array of objects is $.each

success: function(r)
{
  $.each(r, function(index, value){ // iterating over each object

       console.log(value.nm); // <---- accessing nm of each object

  });
}
Dhiraj
  • 33,140
  • 10
  • 61
  • 78
0

You are not iterating upon the result set.

This is much shorter and readable.

$.getJSON("http://mysafeinfo.com/api/data?list=englishmonarchs&format=json", function (data) {

    $.each(data, function (index, value) {
        alert(index + ": " + value.nm);

    });
});

http://jsfiddle.net/5skony7y/2/

Open the Chrome console and you will see the following:

enter image description here

Ali Gajani
  • 14,762
  • 12
  • 59
  • 100