Skip to content

Instantly share code, notes, and snippets.

@sirleech
Created May 11, 2012 14:42
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 20 You must be signed in to fork a gist
  • Save sirleech/2660189 to your computer and use it in GitHub Desktop.
Save sirleech/2660189 to your computer and use it in GitHub Desktop.
Python Read JSON from HTTP Request of URL
# Load Json into a Python object
import urllib2
import json
req = urllib2.Request("http://localhost:81/sensors/temperature.json")
opener = urllib2.build_opener()
f = opener.open(req)
json = json.loads(f.read())
print json
print json['unit']
# Array example
import urllib2
import json
req = urllib2.Request("http://vimeo.com/api/v2/video/38356.json")
opener = urllib2.build_opener()
f = opener.open(req)
json = json.loads(f.read())
print json
print json[0]['title']
@Jaxkr
Copy link

Jaxkr commented May 20, 2013

This is very helpful. Thank you.

@tatoosh
Copy link

tatoosh commented Jan 11, 2015

Thanks, i use your first example. I think the content will be cached. Any solution for that?

@victor-wangl
Copy link

It helps me so much,Thanks

@brentkirkland
Copy link

+1 for you sir

@avbanks
Copy link

avbanks commented Jul 2, 2017

So whats the advantage of using .build_opener instead of urlopen?

@sogrbilja
Copy link

simple and understandable

@earmand
Copy link

earmand commented Jan 18, 2018

I would suggest you don't create a variable named 'json' that overloads the class named 'json' in line 19.

@kusumkumari
Copy link

import requests
import json
import urllib

url="http://api.open-notify.org/iss-pass.json"
r=requests.get(url)
t=json.loads(r.content)
for i in range(len(t)):
print(t[i]['state'])

@abhishtagatya
Copy link

abhishtagatya commented Mar 3, 2018

I would suggest using requests

import requests

r = requests.get('URL-HERE')
print r.json()

@daodennis-zz
Copy link

This is a bit confusing https://gist.github.com/sirleech/2660189#file-gistfile1-py-L19, the variable name is shadowing the library json here. Something like json_response could work better here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment