如何使用Python获取Thingspeak频道的field1值

时间:2018-08-10 07:22:36

标签: python

我想获取Thingspeak频道的field1值。

我收到以下错误:

KeyError: 'field1'.

这是API响应:

{"channel":{"id":556464,"name":"pir","description":"pir","latitude":"0.0","longitude":"0.0","field1":"intrusuion","created_at":"2018-08-08T19:04:03Z","updated_at":"2018-08-08T19:41:06Z","last_entry_id":49},"feeds":[{"created_at":"2018-08-08T19:41:06Z","entry_id":49,"field1":"1\r\n\r\n"}]}

代码

import urllib.request
import json
import time

while True:
    TS = urllib.request.urlopen("https://api.thingspeak.com/channels/556464/feeds.json?results=1")

    response = TS.read()
    data=json.loads(response)
    b = data['field1']
    print (b)
    time.sleep(5)   
    TS.close()

4 个答案:

答案 0 :(得分:1)

有两个不同的属性,名称为field1

您可以通过以下方式访问的第一个:

data['channel']['field1'] # contains "intrusuion"

您可以通过的第二个:

data['feeds'][0]['field1'] # contains "1\r\n\r\n"

答案 1 :(得分:1)

尝试此代码

import urllib.request
import json
import time
from pprint import pprint

while True:
  TS = urllib.request.urlopen("https://api.thingspeak.com/channels/556464/feeds.json?results=1")

  response = TS.read()
  data=json.loads(response)
  pprint(data)
  b = data['channel']['field1']
  print (b)
  time.sleep(5)
  TS.close()

使用pprint检查响应是否具有 feild1 ,然后您可以根据需要打印它

答案 2 :(得分:0)

field1位于键“ channel”和“ feeds”内部。 您可以通过

访问它们
data[the key]['field1']

答案 3 :(得分:0)

{{1}}