javascript 从 JSON 数组中获取变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19787421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get variable from JSON Array
提问by user2894088
I want to get the key from the JSON
Array?
This is my JSON Array
我想从JSON
数组中获取密钥?这是我的 JSON 数组
****JAVASCRIPT****
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];
From this JSON I need the result key. I mean "firstName", "lastName", not John, Anna, Peter Please help to get the keys from JSON.
从这个 JSON 我需要结果键。我的意思是“名字”、“姓氏”,而不是约翰、安娜、彼得 请帮助从 JSON 中获取密钥。
回答by Hasan Alaca
Try this:
试试这个:
http://jsfiddle.net/NJMyD/1072/
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");
});
});
回答by Sridhar R
Try this
试试这个
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
}
Fiddle
小提琴
回答by Lingasamy Sakthivel
I think you need the key
. Object
has a prototype keys which returns an Array of keys in an Object
我认为你需要key
. Object
有一个原型键,它返回一个对象中的键数组
Object.keys(employees); // returns ["firstName", "lastName"]
Also
还
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);
}
}
回答by Hiral
Try this:
试试这个:
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);
});
});
Hope it helps you.
希望对你有帮助。
回答by Uday Hiwarale
If you are saving javascript in external file, save as filename.json
如果您将 javascript 保存在外部文件中,请另存为 filename.json
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];
Then improt filename.json in webpage using jquery as //jquery plugin must be added first
然后在网页中使用 jquery 导入 filename.json as //jquery 插件必须先添加
$(document).ready(function(){
$.getJSON("filename.json",function(result){
alert(result[0].firstname + result[0].lastname);
});
});