2015-11-15 44 views
1

我在從thingspeak獲取數據到json響應中遇到了很多麻煩。我有一個網址,並給了我很多領域的迴應。這是JSON的響應:更改json數組對int數組的響應

?({"channel":{"id":XXXXX,"name":"XXXXX","field1":"Temperature","field2":"Humidity","created_at":"2015-11-03T13:12:06Z","updated_at":"2015-11-15T12:07:37Z","last_entry_id":142},"feeds":[{"created_at":"2015-11-14T21:06:16Z","entry_id":136,"field1":"0"},{"created_at":"2015-11-14T21:06:39Z","entry_id":137,"field1":"25"},{"created_at":"2015-11-14T21:06:59Z","entry_id":138,"field1":"24.05"},{"created_at":"2015-11-14T21:07:13Z","entry_id":139,"field1":"24.45"},{"created_at":"2015-11-14T21:08:16Z","entry_id":140,"field1":"24.45"},{"created_at":"2015-11-15T12:06:18Z","entry_id":141,"field1":"24.5"},{"created_at":"2015-11-15T12:07:37Z","entry_id":142,"field1":"21.4"}]}) 

我想檢索每個field1數據的最大值和最小值。我一直在閱讀和響應不在int中,因此應轉換爲一個int數組。

這是我的代碼的時刻:

$.getJSON('http://api.thingspeak.com/channels/'+channel+'/field/1.json?callback=?', 
       {key: read_API_key, days: "1"}, 
       function(data) { 
        $.each(data.feeds, function() { 
         var temp_vals = this.field1; 
         var temp_vals_date = this.created_at; 
         console.log(temp_vals); 
        }); 
       } 
      ); 

我要搜索飼料數組中尋找FIELD1數量和保存到一個int數組使用Math.max.apply(Math, temp_vals);使用控制檯,值後做數學正確保存到temp_vals,但我不能使用該功能,並出現以下錯誤:Function.prototype.apply: Arguments list has wrong type

因此,如何將響應更改爲int數組或某物以便能夠找到最大值和最小值?另一個快速問題是,打印$ .each(data.feeds,function(){});之外的任何值的方法,因爲我沒有找到辦法做到這一點....

更改爲parseInt函數:

$.getJSON('http://api.thingspeak.com/channels/'+channel+'/field/1.json?callback=?', 
       {key: read_API_key, days: "1"}, 
       function(data) { 
        $.each(data.feeds, function() { 
         var temp_vals = parseInt(this.field1); 
         var temp_vals_date = this.created_at; 
         var temp_max = Math.max.apply(Math, temp_vals); 
         console.log(temp_max); 

         $('#temp1_max').text(temp_max + ' ºC'); 

         console.log(temp_vals); 
        }); 
       } 
      ); 

回答

1

使用parseInt

var temp_vals = parseInt(this.field1); 

編輯:

$.getJSON('http://api.thingspeak.com/channels/'+channel+'/field/1.json?callback=?', 
       {key: read_API_key, days: "1"}, 
       function(data) { 
       var temp_vals = []; 
        $.each(data.feeds, function() { 
         temp_vals.push(parseInt(this.field1)); 
         var temp_vals_date = this.created_at; 
        }); 
        var temp_max = Math.max.apply(Math, temp_vals); 
        console.log(temp_max); 
        console.log(temp_vals); 
        $('#temp1_max').text(temp_max + ' ºC'); 
       } 
      ); 
+0

我仍然有同樣的問題,當做數學函數...我認爲這個問題不是int – CapAm

+0

也許是因爲'var temp_vals'重新定義每個'data.feeds'條目的變量。在AJAX請求之外定義它,然後將結果推送到它:'temp_vals.push(parseInt(this.field1));' – Moin

+0

它說:'不能讀取undefined'的屬性'push',並且日誌不顯示任何東西。所以我不知道我是否收到了一些價值。我將再次檢查以解決此問題。 – CapAm