Search code examples
javascriptjqueryjsonajaxajaxform

How to store JSON data from Github Gist to an array with AJAX method?


I am trying to store JSON data in a variable, later randomly access it. (Random Superhero Name)

JSON data is GitHub gist below

https://gist.githubusercontent.com/abroroo/004fa0a28b94bc7100b4f1bf53acb69d/raw/09fd4ca4ed1ddb21010a48502cf0846a844b658c/authors.json

I am trying to use the ajax method(first time), and I think it is not working. I am getting undefined in the console.

Here is my code:

var namesData;

function getNames() {
  return $.ajax({
    headers: {
      Accept: 'application/json'
    },
    url: 'https://gist.githubusercontent.com/abroroo/004fa0a28b94bc7100b4f1bf53acb69d/raw/09fd4ca4ed1ddb21010a48502cf0846a844b658c/authors.json',
    success: function (jsonNames) {
        namesData = JSON.parse(jsonNames);
        console.log('namesData');
        console.log(namesData);
    }
  });
}

Here is the function to get random names


function getRandomName() {
  return namesData.names[
    Math.floor(Math.random() * namesData.names.length)
  ];
}
console.log(getRandomName());

Any help is appreciated!


Solution

  • I checked you gist json file,it has syntax error. the origin json is

    [
      "names": [
        {
            "superhero":"Batman", 
            "publisher":"DC Comics", 
            "alter_ego":"Bruce Wayne",
            "first_appearance":"Detective Comics #27",
            "characters":"Bruce Wayne"
        },
    

    there should not have key under array.so change root array to dict like this

    {
      "names": [
        {
            "superhero":"Batman", 
            "publisher":"DC Comics", 
            "alter_ego":"Bruce Wayne",
            "first_appearance":"Detective Comics #27",
            "characters":"Bruce Wayne"
        },