简体   繁体   English

在Javascript中从JSON创建一个数组

[英]Create an array from JSON in Javascript

I've researched quite a bit on here and I can't seem to find something that will work for me. 我在这里研究了很多,我似乎无法找到适合我的东西。 What I have is an application that I'm trying to have go out and return the next four bus arrival times for a bus stop. 我所拥有的是一个应用程序,我正试图出去并返回公共汽车站的下四个公交车到达时间。 I am reaching out to an API that returns this data in a JSON file. 我正在寻找一个在JSON文件中返回此数据的API。 The problem I am having is I can see my request go out via fiddler but I can't seem to get the data into an array. 我遇到的问题是我可以通过提琴手看到我的请求,但我似乎无法将数据放入数组中。 Below is the code that I'm dealing with right now. 下面是我正在处理的代码。 I'm trying to get the returned data into a table format which you can see I'm failing at. 我正在尝试将返回的数据转换为表格格式,您可以看到我失败了。

Eventually I want to get a popup to appear when the user clicks on the Show me the next 4 bus arrival times but this was for testing purposes. 最后,当用户点击向我显示接下来的4个公交车到达时间时,我想要弹出窗口,但这是出于测试目的。 I would love to have the users click on my button which calls this function and then something like a like table open with these values. 我希望让用户点击我的按钮来调用这个函数,然后像这样的表打开这些值。 If you can help with that within this code I would appreciate it as well. 如果你能在这段代码中提供帮助,我也会很感激。

JSON Data: JSON数据:

[{"ARRIVAL":"01:23P","ROUTE":"208","DIR":"E"},
{"ARRIVAL":"01:53P","ROUTE":"208","DIR":"E"},
{"ARRIVAL":"02:23P","ROUTE":"208","DIR":"E"},
{"ARRIVAL":"02:53P","ROUTE":"208","DIR":"E"}]

Code: 码:

<script>
function getTimes(stopNumber) {
        var busArrivalAPI = "http://blahblahblah/rtcTimes/" + stopNumber ";
        $.getJSON(busArrivalAPI, function(busArrivals) {
            var a = [];
            for (var i = 0; i < busArrivals.length; i++) {
                a[i] = [busArrivals[i].ROUTE, busArrivals[i].ARRIVAL, busArrivals[i].DIR];
                document.getElementById("results").createElement("TR");
                for (var b = 0; b < 3; b++) {
                    var x = document.createElement("TH");
                    var z = a[i][b];
                    var t = document.createTextNode(z);
                    x.appendChild(t);
                    document.getElementById('results').appendChild(x);
                };
            };
        });     
</script>

My DIV: 我的DIV:

<div style="overflow-x:scroll; overflow-y:scroll;" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="title:'Bus Arrival Times', selected:true">
  <table id = 'results'>
    <tr>
      <th>Route</th>
      <th>Arrival Time</th>
      <th>Direction</th>
    </tr>
  </table>
</div>

UPDATE: Ok, I've use the makeTable idea provide below and it works when I program as seen below hard coding the json data. 更新:好的,我使用下面提供的makeTable想法,它可以在我编程时工作,如下所示硬编码json数据。 However, when trying to use the $.getJSON I'm having some cross domain issues now and don't know how I can get my $.getJSON request working. 但是,在尝试使用$ .getJSON时,我现在遇到了一些跨域问题,并且不知道如何让我的$ .getJSON请求正常工作。 Any input on how to get the data from my getJSON request work be great. 有关如何从我的getJSON请求获取数据的任何输入都很有用。

function getTimes(stopNumber) {

    // This is the API address I need to hit.  Trying to figure out how to incorporate that and remove the function getJSON where I have the data hard coded.
    //var busArrivalAPI = "http://-----/rtcTimes/"+ stopNumber + "?jsoncallback=?";    

    function makeTable(busArrivals) {
    // This will remove old values so table will only load current Times
      var results = document.getElementById("results");
      var rowCount = results.rows.length;
      for (var x=rowCount-1; x>0; x--) {
        results.deleteRow(x);
      }
      //  This will populate the result table with the correct bus routes/times/direction
      busArrivals.forEach(function(busArrival) {
        var tr = document.createElement('tr');
        var route = document.createElement('td');
        route.appendChild(document.createTextNode(busArrival.ROUTE));
        var arrival = document.createElement('td');
        arrival.appendChild(document.createTextNode(busArrival.ARRIVAL));
        var direction = document.createElement('td');
        direction.appendChild(document.createTextNode(busArrival.DIR));
        tr.appendChild(route);
        tr.appendChild(arrival);
        tr.appendChild(direction);
        document.getElementById('results').appendChild(tr);
      });
    }

    function getJSON(callback) {
      var data = [{"ARRIVAL":"05:23P","ROUTE":"201","DIR":"E"},
        {"ARRIVAL":"05:54P","ROUTE":"202","DIR":"E"},
        {"ARRIVAL":"06:33P","ROUTE":"203","DIR":"E"},
        {"ARRIVAL":"07:11P","ROUTE":"204","DIR":"E"}];
        callback(data);
    }

    getJSON(makeTable);
  };

I think you could write a separate function to build the table, like this: 我想你可以编写一个单独的函数来构建表,如下所示:

function makeTable(busArrivals) {
    busArrivals.forEach(function(busArrival) {
        var tr = document.createElement('tr');
        var route = document.createElement('td');
        route.appendChild(document.createTextNode(busArrival.ROUTE));
        var arrival = document.createElement('td');
        arrival.appendChild(document.createTextNode(busArrival.ARRIVAL));
        var direction = document.createElement('td');
        direction.appendChild(document.createTextNode(busArrival.DIR));
        tr.appendChild(route);
        tr.appendChild(arrival);
        tr.appendChild(direction);
        document.getElementById('results').appendChild(tr);
    });
}

var busArrivalAPI = 'http://blahblahblah/rtcTimes/'+ stopNumber;
$.getJSON(busArrivalAPI, makeTable);

In each iteration of the forEach loop, you construct a tr element, insert the tds and finally put the whole thing inside the DOM. 在forEach循环的每次迭代中,构造一个tr元素,插入tds并最终将整个东西放入DOM中。

You're creating a TR element, but never appending it to the table. 您正在创建一个TR元素,但从不将其附加到表中。 Instead, you're appending the TH elements directly to the table, which is invalid. 相反,您将TH元素直接附加到表中,这是无效的。

function getTimes(stopNumber) {
    var busArrivalAPI = "http://blahblahblah/rtcTimes/" + stopNumber;
    $.getJSON(busArrivalAPI, function(busArrivals) {
        var table = document.getElementById('results');
        for (var i = 0; i < busArrivals.length; i++) {
            var a = [busArrivals[i].ROUTE, busArrivals[i].ARRIVAL, busArrivals[i].DIR];
            var row = document.createElement("TR");
            for (var b = 0; b < 3; b++) {
                var x = document.createElement("TH");
                var z = a[b];
                var t = document.createTextNode(z);
                x.appendChild(t);
                row.appendChild(x);
            };
            table.appendChild(row);
        };
    });
}

I'm not sure why you need the a array. 我不确定你为什么需要a阵列。 If you just want to change get the object properties into an array so you can iterate over it, you can do that with a 1-dimensional array, you don't need to save all the other rows in a 2-dimensional array. 如果您只想将对象属性更改为数组,以便可以对其进行迭代,则可以使用1维数组执行此操作,而无需将所有其他行保存在2维数组中。 I've changed a to a single array. 我已将a更改为单个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM