从JSON数组中获取变量

时间:2013-11-05 11:00:49

标签: javascript jquery arrays json

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

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

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

5 个答案:

答案 0 :(得分:2)

试试这个:

<强> 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");
    });
});

答案 1 :(得分:0)

试试这个

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/

答案 2 :(得分:0)

我认为你需要keyObject有一个原型键,它返回一个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);
    }
}

答案 3 :(得分:0)

试试这个:

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);                        
    });
}); 

Fiddle here:

希望它对你有所帮助。

答案 4 :(得分:0)

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

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

然后使用jquery as在网页中improt filename.json //必须首先添加jquery插件

$(document).ready(function(){
$.getJSON("filename.json",function(result){
alert(result[0].firstname + result[0].lastname);
});
});