我有一个json数组说
{
"People": {
"Person": [
{"FirstName": "John", "LastName": "Smith"}
{"FirstName": "Joe", "LastName": "Bloggs"}
{"FirstName": "Wendy", "LastName": "Deng"}
]
}
}
我希望将其转换为javascript
数组(类似于此)
var persons = [ ["FirstName", "John", "LastName", "Smith"], ["FirstName", "Joe", "LastName", "Bloggs"], ["FirstName", "Wendy", "LastName": "Deng"] ];
我如何做到这一点?希望我的问题有道理,我意识到javascript数组初始化可能不是正确的方法。
感谢。
答案 0 :(得分:1)
jsfiddle demo:here
var src={
"People": {
"Person": [
{"FirstName": "John", "LastName": "Smith"},
{"FirstName": "Joe", "LastName": "Bloggs"},
{"FirstName": "Wendy", "LastName": "Deng"}
]
}
};
var persons=[];
var obj=src["People"]["Person"];
for(i in obj){
var temp=[];
temp.push("FirstName");
temp.push(obj[i].FirstName);
temp.push("LastName");
temp.push(obj[i].LastName);
persons.push(temp);
}
// persons contain your requried array
答案 1 :(得分:0)
你要做的事情并没有多大意义。将现有的有效JSON对象转换为您指定的数组格式是毫无意义的,并且会使访问元素变得困难。
听起来你真正想做的是:
var data = JSON.parse(jsonString); // Your JSON, parsed into a JS object.
var persons = []
data.people.person.foEach( function(el) {
person.push(el.FirstName + " " + el.LastName);
}
现在persons
看起来像这样:
["John Smith", "Joe Bloggs", "Wendy Deng"]
您确定知道JSON和JavaScript对象是如何工作的吗?
var myJSON = '{ "foo": { "bar": { "baz" : [1,2,3] } } }' // JSON, String type.
var myObj = JSON.parse(myJSON); // Now a JS Object type.
var innerArray = myObj.foo.bar.baz;
现在,变量innerArray
的值为[1,2,3]
,Array
类型。
console.log(innerArray[0]); // Log the first element.
> 1 // First element is 1