最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to put the contents of a json file into an array using Javascript? - Stack Overflow

programmeradmin7浏览0评论

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

{
    "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]"
    }
}

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

{
    "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]"
    }
}
Share Improve this question edited Feb 10, 2024 at 11:29 gary 4,2553 gold badges33 silver badges58 bronze badges asked Jan 26, 2013 at 18:41 KakitoriKakitori 9136 gold badges16 silver badges41 bronze badges 3
  • Is this external file on your own server? – Explosion Pills Commented Jan 26, 2013 at 18:43
  • Here is some useful information about it: api.jquery./jQuery.getJSON. – VisioN Commented Jan 26, 2013 at 18:43
  • 1 yeah, this file is in my server – Kakitori Commented Jan 26, 2013 at 18:46
Add a ment  | 

3 Answers 3

Reset to default 13

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
        });            
    }
}
});
var items = [];
$.each(JSONObject.results.bindings, function(i, obj) {
    items.push([obj.place.value, obj.lat.value, obj.long.value, obj.page.value]);
});

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(',')+']');
发布评论

评论列表(0)

  1. 暂无评论