javascript 如何获取json文件的数组javascript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14540248/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:54:56  来源:igfitidea点击:

how to get an array javascript of json file?

javascriptjqueryarraysjson

提问by Kakitori

I have an external file contacts.json. How I can convert it to a javascript array?
this is the contacts.jsoncontent:

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

{
    "ppl1":{
        "Name":"Jhon",
        "Surname":"Kenneth",
        "mobile":329129293,
        "email":"[email protected]"
    },
    "ppl2":{
        "Name":"Thor",
        "Surname":"zvalk",
        "mobile":349229293,
        "email":"[email protected]"
    },
    "ppl3":{
        "Name":"Mila",
        "Surname":"Kvuls",
        "mobile":329121293,
        "email":"[email protected]"
    }
}

回答by Kakitori

Solved:

解决了:

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

回答by Norbert Pisz

var items = [];
$.each(JSONObject.results.bindings, function(i, obj) {
    items.push([obj.place.value, obj.lat.value, obj.long.value, obj.page.value]);
});

回答by JakeGould

Answered over here.

在这里回答。

// JavaScript array of JavaScript objects
var objs = json_string.map(JSON.parse);

// ...or for older browsers
var objs=[];
for (var i=json_string.map.length;i--;) objs[i]=JSON.parse(json_string.map[i]);

// ...or for maximum speed:
var objs = JSON.parse('['+json_string.map.join(',')+']');