0

我有一个外部文件people.json。如何将其转换为具有 json 语法的 javascript 数组?
这是people.json的内容:

{
"1":{
    "Name":"Jhon",
    "Surname":"Kenneth",
    "mobile":329129293,
    "email":"jhon@gmail.com"
},
"2":{
    "Name":"Thor",
    "Surname":"zvalk",
    "mobile":349229293,
    "email":"thor@gmail.com"
},
"3":{
    "Name":"Mila",
    "Surname":"Kvuls",
    "mobile":329121293,
    "email":"mila@gmail.com"
}
}

我想要一个这种格式的数组

var person = [
{ "name":"jhon" , "surname":"kenneth", "mobile":329129293, "email":"jhon@gmail.com"}, 
{ "Name":"Thor", "Surname":"zvalk", "mobile":349229293, "email":"thor@gmail.com" }, 
{ "Name":"Mila", "Surname":"Kvuls", "mobile":329121293, "email":"mila@gmail.com"}
];

我尝试使用下一个代码,但它不起作用:

 var person;   
$.getJSON('people.json', function (json) {
person[]= json
});

顺便说一句,文件contacts.json 在我的服务器中。

4

5 回答 5

4

可以使用 jQuery$.map()

var newArray=$.map( originalObject, function(item){
    return item;
})

演示:http: //jsfiddle.net/qmfn2/

于 2013-01-26T19:52:33.573 回答
3

试试这样:

$.getJSON('people.json', function (json) {
    var people = [];
    for (var key in json) {
        if (json.hasOwnProperty(key)) {
            var item = json[key];
            people.push({
                name: item.Name,
                surname: item.Surname,
                mobile: item.mobile,
                email: item.email
            });            
        }
    }

    // at this stage the people object will contain the desired output
});
于 2013-01-26T19:49:23.110 回答
1

首先,您需要使用 AJAX 请求获取 JSON 文件。然后遍历接收到的 JSON 对象并将每个属性添加到数组中。

function convertToArray (receivedObj) {
    var array = [], key;
    for (key in receivedObj) {
        array.push(receivedObj[key]);
    }
    return array;
}

$.getJSON('people.json', function (json) {
    var array = convertToArray(json);
});

希望这可以帮助!

于 2013-01-26T19:50:44.373 回答
1

像这样:

var array = $.map($.parseJSON(data), Object);

http://jsfiddle.net/mXFKL/

于 2013-01-26T20:04:21.457 回答
1
$.getJSON('people.json', function (json) {
var array = convertToArray(json);
});
于 2013-01-29T18:40:07.587 回答