简体   繁体   English

来自网址的Python解析JSON响应

[英]Python Parse JSON Response from URL

I'm am wanting to get information about my Hue lights using a python program. 我想使用python程序获取有关我的Hue灯的信息。 I am ok with sorting the information once I get it, but I am struggling to load in the JSON info. 一旦获得信息,我就可以对信息进行排序,但是我正努力加载JSON信息。 It is sent as a JSON response. 它作为JSON响应发送。 My code is as follows: 我的代码如下:

import requests
import json

response= requests.get('http://192.168.1.102/api/F5La7UpN6XueJZUts1QdyBBbIU8dEvaT1EZs1Ut0/lights')
data = json.load(response)   
print(data)

When this is run, all I get is the error: 运行此命令时,我得到的只是错误:

in load return loads(fp.read(),    
Response' object has no attribute 'read'

The problem is you are passing in the actual response which consists of more than just the content. 问题是您要传递的实际响应不仅仅是内容。 You need to pull the content out of the response: 您需要从响应中拉出内容:

import requests
r = requests.get('https://github.com/timeline.json')
print r.text

# The Requests library also comes with a built-in JSON decoder,
# just in case you have to deal with JSON data

import requests
r = requests.get('https://github.com/timeline.json')
print r.json

http://www.pythonforbeginners.com/requests/using-requests-in-python http://www.pythonforbeginners.com/requests/using-requests-in-python

Looks like it will parse the JSON for you already... 看起来它已经为您解析了JSON ...

Use response.content to access response content and json.loads method instead of json.load: 使用response.content访问响应内容和json.loads方法,而不是json.load:

data = json.loads(response.content)  
print data

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

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