Dorothy
Dorothy

Reputation: 61

Python Parse JSON Response from URL

I'm am wanting to get information about my Hue lights using a python program. I am ok with sorting the information once I get it, but I am struggling to load in the JSON info. It is sent as a JSON response. 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'

Upvotes: 0

Views: 9780

Answers (2)

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22071

Use response.content to access response content and json.loads method instead of json.load:

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

Upvotes: 1

GantTheWanderer
GantTheWanderer

Reputation: 1292

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

Looks like it will parse the JSON for you already...

Upvotes: 1

Related Questions