如何获取JSON对象中的所有键(javascript)

时间:2014-11-13 05:31:32

标签: javascript json

{"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

从这个JSON示例中,我想为每个人获取nameagegender等密钥。

怎么做?

6 个答案:

答案 0 :(得分:21)

试试这个

var s = {name: "raul", age: "22", gender: "Male"}
   var keys = [];
   for(var k in s) keys.push(k);

此处,键数组将返回您的键["name", "age", "gender"]

答案 1 :(得分:21)

我使用内置于JavaScript Object中的Object.keys,它将返回给定对象MDN Reference

中的键数组
var obj = {name: "Jeeva", age: "22", gender: "Male"}
console.log(Object.keys(obj))

答案 2 :(得分:13)

var input = {"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
    Object.keys(input.document.people[i]).forEach(function(key){
        if(keys.indexOf(key) == -1)
        {
            keys.push(key);
        }
    });
}
console.log(keys);

答案 3 :(得分:4)

这一天的ES6;

const json_getAllKeys = data => (
  data.reduce((keys, obj) => (
    keys.concat(Object.keys(obj).filter(key => (
      keys.indexOf(key) === -1))
    )
  ), [])
)

是的,它可以写成很长的一行;

const json_getAllKeys = data => data.reduce((keys, obj) => keys.concat(Object.keys(obj).filter(key => keys.indexOf(key) === -1)), [])

编辑:如果输入类型为对象数组

,则返回所有一阶键

答案 4 :(得分:2)

var jsonData = { Name: "Ricardo Vasquez", age: "46", Email: "Rickysoft@gmail.com" };

for (x in jsonData) {   
  console.log(x +" => "+ jsonData[x]);  
  alert(x +" => "+  jsonData[x]);  
  }

答案 5 :(得分:0)

我们必须“解析”我们的 jsonObject

 console.log('{"key0":"value0", "key1":"value1"}'); 
    var jsonObject = JSON.parse('{"key0":"value0", "key1":"value1"}')
    Object.keys(jsonObject).forEach(key => { 
        console.log(jsonObject[key]); //values 
        console.log(key); //keys 
    })