Teisman
Teisman

Reputation: 1358

Unable to access element in JSON when keyname is unknown

I'm trying to retrieve the filename of gists on Github, from the data obtained from Github's API. I'm using javascript to access the data.

An example result can be found here: https://api.github.com/users/blaercom/gists. I've also copied a shortened version of the data below.

{
  ...
  id: "4468273",
  files: {
    firstpost.md: {
      type: "text/plain",
      filename: "firstpost.md",
      size: 16,
      language: "Markdown"
    }
  }
  ...
}

I've been trying many things, but I can't seem to access the filename. This is because the 'files' object is not a list, but a key-value pair, where the key identifier matches the filename itself.

Things I've tried include

filename = files[0]['filename']
filename = files[0].filename
filename = files['filename']

Frankly, the only methods that work are variations of filename = files['firstpost.md']['filename'] but this isn't valid since I can not know the filename beforehand.

I'm sure it is possible to access the filename, but have been spending quite a while testing different methods. Help would be appreciated!

Upvotes: 1

Views: 117

Answers (2)

user625860
user625860

Reputation:

You can use for (var key in object) {}, here is an example using the data from your api call:

var filenames = [];

for (var filename in data[0].files) {
   filenames.push(filename);
}

console.log(filenames); // ["firstpost.md"]

Upvotes: 4

The Alpha
The Alpha

Reputation: 146191

Here is a real example using your json response

var obj='your json data';
var fileNames=[];
for(var i in obj[0]['files'])
{
    var fileName=obj[0]['files'][i]['filename'];
    fileNames.push(fileName);
}
document.write(fileNames[0]); // firstpost.md

Example.

Update:

Another example using jsonp/script.

<script src="https://api.github.com/users/blaercom/gists?callback=myCallback"></script>

The callback function

function myCallback(o)
{
    var obj=o.data;
    var fileNames=[];
    for(var i in obj[0]['files'])
    {
        var fileName=obj[0]['files'][i]['filename'];
        fileNames.push(fileName);
    }
    document.write(fileNames[0]);  // firstpost.md
}

Upvotes: 1

Related Questions