使用AJAX读取JSON文件并将数据存储到数组

时间:2018-11-27 06:15:51

标签: javascript ajax

我要做的就是读取具有如下所示数据格式的JSON文件,并仅从节点中提取id并将其存储在数组中。

{"nodes":[
{"id":"1057457211927117824", "age":"20", "name":"a", "loaded":true},
{"id":"1057459284189970433", "age":"20", "name":"b", "loaded":true}
]
"links":[
{"id":"l01", "from":"1057457210467540992", "to":"1057455883972722689", "type":"friend"},
{"id":"l02", "from":"1057457271331057664", "to":"1057451606344646656", "type":"friend"}
]}

下面是我尝试过的代码,但是没有用。

var node_id = []; 
$.getJSON("data/newData.json", function (data) {
    $.each(data, function (index, value) {
        node_id.push(value[0]['id']); 
    });
});

1 个答案:

答案 0 :(得分:2)

如果我了解您,则可以查看以下代码:

var jsonData = {
"nodes":[
  {"id":"1057457211927117824", "age":"20", "name":"a", "loaded":true},
  {"id":"1057459284189970433", "age":"20", "name":"b", "loaded":true}],
"links":[
  {"id":"l01", "from":"1057457210467540992", "to":"1057455883972722689", "type":"friend"},
  {"id":"l02", "from":"1057457271331057664", "to":"1057451606344646656", "type":"friend"}
]};

var node_id = []; 
$.each(jsonData.nodes, function (index, value) {
    node_id.push(value['id']); 
});

console.log(node_id);
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>