Skip to content Skip to sidebar Skip to footer

How To Read Keys From JSON Object

I have the following JSON (truncated): { '** Please contact a mod by posting on the forums **': { 'tvdb_id': '257937', 'last_updated': 1341780286, 'imag

Solution 1:

In your example the value you have is the key, so just use it to access the property you want..

var somevalue = 'Jamies Best Ever Christmas',
    tvdb_id = jsonobj[somevalue].tvdb_id;

Solution 2:

In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:

var keys = Object.keys(myJsonObject);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

You may use the one below as well:

var getKeys = function(obj){
   var keys = [];
   for(var key in obj){
      keys.push(key);
   }
   return keys;
}

Solution 3:

It looks like you're using Underscore.js.

Gaby's answer should fit the bill. However, if you're looking for partial matches, Underscore.js has some cool features in it. Consider this:

var mappedResults = _.map(jsonobj, function(key, value, list) {
    return {name:key, tvdb_id:value.tvdb_id};
});

This will give you an array of objects, each with the title and the tvdb id.

To execute searches, you could write a function like this:

function getMatchingIds(searchterm) {
    return _.filter(mappedResults, function(entry) {
        return (entry.name.indexOf(searchterm) != -1);
    });
}

Post a Comment for "How To Read Keys From JSON Object"