我有很多麻烦将来自thingspeak的数据转换为json响应。我有一个网址,其响应给了我很多领域。这是JSON的响应:
?({"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);
});
}
);
我想在feed数组中搜索,查找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);
});
}
);
答案 0 :(得分: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');
}
);