从json" feed"获取时间序列。

时间:2016-07-26 15:32:39

标签: javascript arrays json

虽然ThingSpeak拥有出色的图表,但我希望从ThingSpeak获取数据并使用Google Charts创建自己的图表。获得"饲料"来自ThingSpeak," feed"是一个像这样的JSON对象:

{
  "channel":
  {
     "id": 9,
     "name": "my_house",
     "description": "Netduino Plus connected to sensors around the house",
     "latitude": "40.44",
     "longitude": "-79.996",
     "field1": "Light",
     "field2": "Outside Temperature",
     "created_at": "2010-12-13T20:20:06-05:00",
     "updated_at": "2014-02-26T12:43:04-05:00",
     "last_entry_id": 6060625
  },
  "feeds":
       [
          {
            "created_at": "2014-02-26T12:42:49-05:00",
            "entry_id": 6060624,
            "field1": "188",
            "field2": "25.902335456475583"
          },
          {
            "created_at": "2014-02-26T12:43:04-05:00",
            "entry_id": 6060625,
            "field1": "164",
            "field2": "25.222929936305732"
          }
      ]
  }

我花了很长时间寻找一种方法来提取" created_at"和" field1" (也许" field2")数据到一个表/数组,但我还没能弄明白。我正瞄准这些方面的事情:

[
['created_at',                'field1', 'field2'],
['2014-02-26T12:42:49-05:00', 188,      25.902335456475583],
['2014-02-26T12:43:04-05:00', 164,      25.222929936305732]
]

我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

这是我怎么做的。 (注意:我使用此处的代码来确定如何获取标题:How to iterate through property names of Javascript object?



var j = {
  "channel":
  {
     "id": 9,
     "name": "my_house",
     "description": "Netduino Plus connected to sensors around the house",
     "latitude": "40.44",
     "longitude": "-79.996",
     "field1": "Light",
     "field2": "Outside Temperature",
     "created_at": "2010-12-13T20:20:06-05:00",
     "updated_at": "2014-02-26T12:43:04-05:00",
     "last_entry_id": 6060625
  },
  "feeds":
       [
          {
            "created_at": "2014-02-26T12:42:49-05:00",
            "entry_id": 6060624,
            "field1": "188",
            "field2": "25.902335456475583"
          },
          {
            "created_at": "2014-02-26T12:43:04-05:00",
            "entry_id": 6060625,
            "field1": "164",
            "field2": "25.222929936305732"
          }
      ]
  }

var results = [];
var feeds = j.feeds;

var headers = [];
for (var key in feeds[0]) {
    headers.push(key);
}
results.push(headers);

for (var x = 0; x < feeds.length; x++) {
    var row = [];
    var feed = feeds[x];
    for (var y = 0; y < headers.length; y++) {
        var header = headers[y];
        row.push(feed[header]);
    }
    results.push(row);
}

console.log(results);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;