我想从JSON
数组中获取密钥?
这是我的JSON数组
****JAVASCRIPT****
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];
从这个JSON我需要结果键。我的意思是“firstName”,“lastName”,而不是John,Anna,Peter 请帮助从JSON获取密钥。
答案 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
}
小提琴
答案 2 :(得分:0)
我认为你需要key
。 Object
有一个原型键,它返回一个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);
});
});
希望它对你有所帮助。
答案 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);
});
});