1

我想从JSON数组中获取密钥?这是我的 JSON 数组

****JAVASCRIPT****
var employees = [
                 { "firstName":"John" , "lastName":"Doe" }, 
                 { "firstName":"Anna" , "lastName":"Smith" }, 
                 { "firstName":"Peter" , "lastName": "Jones" }
               ];

从这个 JSON 我需要结果键。我的意思是“firstName”、“lastName”,而不是 John、Anna、Peter 请帮助从 JSON 中获取密钥。

4

5 回答 5

4

试试这个:

http://jsfiddle.net/NJMyD/1072/

var employees = '[{"firstName":"John","lastName":"Doe" },{"firstName":"Anna","lastName":"Smith" },{"firstName":"Peter","lastName":"Jones"}]';

var myData = JSON.parse(employees);

$(document).ready(function() {
    $.each(myData, function() {
        $('<li>' + this.firstName + ' ' + this.lastName + '</li>').appendTo("#groups");
    });
});
于 2013-11-05T11:13:28.933 回答
2

如果您将 javascript 保存在外部文件中,请另存为 filename.json

var employees = [
                 { "firstName":"John" , "lastName":"Doe" }, 
                 { "firstName":"Anna" , "lastName":"Smith" }, 
                 { "firstName":"Peter" , "lastName": "Jones" }
               ];

然后在网页中使用jquery作为导入filename.json //必须先添加jquery插件

$(document).ready(function(){
$.getJSON("filename.json",function(result){
alert(result[0].firstname + result[0].lastname);
});
});
于 2013-11-05T11:17:22.357 回答
1

试试这个

var employees = [
             { "firstName":"John" , "lastName":"Doe" }, 
             { "firstName":"Anna" , "lastName":"Smith" }, 
             { "firstName":"Peter" , "lastName": "Jones" }
           ]; //your array

for(var i in employees)
{
var fname=employees[i].firstName
var lname=employees[i].lastName
console.log(fname) //all first names
console.log(lname) //all last names
}

小提琴

http://jsfiddle.net/8TB6Z/

于 2013-11-05T11:04:02.423 回答
1

我认为你需要key. Object有一个原型键,它返回一个对象中的键数组

Object.keys(employees); // returns ["firstName", "lastName"]

for(i in employees){
var key = i;
var val = employees[i];
for(j in val)
    {
    var sub_key = j;
    var sub_val = val.j;
    console.log(sub_key);
    }
}
于 2013-11-05T11:10:51.837 回答
1

试试这个:

var employees = [
    { "firstName":"John" , "lastName":"Doe" }, 
    { "firstName":"Anna" , "lastName":"Smith" }, 
    { "firstName":"Peter" , "lastName": "Jones" }
];
$.each(employees,function(f,n){                    
    $.each(n,function(ff,nn){
        console.log("field:"+ff+" value:"+nn);                        
    });
}); 

在这里提琴:

希望它可以帮助你。

于 2013-11-05T11:16:04.553 回答