158

I have a json-object in JavaScript and I want to get the used keys in it. My JavaScript-Code looks like this:

var jsonData = [{"person":"me","age":"30"},{"person":"you","age":"25"}];

And I want a loop that alerts me 'person' and 'age', which are the keys of the first object in the json-Array.

2
  • 8
    That's a JavaScript array/object, not JSON. Commented Dec 8, 2011 at 11:32
  • 3
    yes its a duplicat. but I didn't know what I was looking for... Commented Dec 8, 2011 at 11:42

3 Answers 3

292
var jsonData = [{"person":"me","age":"30"},{"person":"you","age":"25"}];

for(var i in jsonData){
    var key = i;
    var val = jsonData[i];
    for(var j in val){
        var sub_key = j;
        var sub_val = val[j];
        console.log(sub_key);
    }
}

EDIT

var jsonObj = {"person":"me","age":"30"};
Object.keys(jsonObj);  // returns ["person", "age"]

Object has a property keys, returns an Array of keys from that Object

Chrome, FF & Safari supports Object.keys

Sign up to request clarification or add additional context in comments.

4 Comments

This should be accepted as the correct answer. Very efficient!
is there an es6/es7 syntax to simplify this method?
I was struggling to find a method that will work with Rhino. This was it. +1
I am trying to convert rows from DB to JSON. I am getting numerical index along with actual column names as keys. Why I am getting numerical index?
139

[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]

If you can rely on having ECMAScript5 features available, you can use the Object.keys function to get an array of the keys (property names) in an object. All modern browsers have Object.keys (including IE9+).

Object.keys(jsonData).forEach(function(key) {
    var value = jsonData[key];
    // ...
});

The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim).

Here's the rest of the answer from 2011:

Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:

if (typeof Object.keys !== "function") {
    (function() {
        var hasOwn = Object.prototype.hasOwnProperty;
        Object.keys = Object_keys;
        function Object_keys(obj) {
            var keys = [], name;
            for (name in obj) {
                if (hasOwn.call(obj, name)) {
                    keys.push(name);
                }
            }
            return keys;
        }
    })();
}

That uses a for..in loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty to check that the property is owned directly by the object rather than being inherited.

(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)

Comments

25

The working code

var jsonData = [{person:"me", age :"30"},{person:"you",age:"25"}];

for(var obj in jsonData){
    if(jsonData.hasOwnProperty(obj)){
    for(var prop in jsonData[obj]){
        if(jsonData[obj].hasOwnProperty(prop)){
           alert(prop + ':' + jsonData[obj][prop]);
        }
    }
}
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.