Python 3 Get and parse JSON API
Version 1: (do a pip install requests
before running the script)
import requestsr = requests.get(url='https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty')print(r.json())
Version 2: (do a pip install wget
before running the script)
import wgetfs = wget.download(url='https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty')with open(fs, 'r') as f: content = f.read()print(content)
you can use standard library python3:
import urllib.requestimport jsonurl = 'http://www.reddit.com/r/all/top/.json'req = urllib.request.Request(url)##parsing responser = urllib.request.urlopen(req).read()cont = json.loads(r.decode('utf-8'))counter = 0##parcing jsonfor item in cont['data']['children']: counter += 1 print("Title:", item['data']['title'], "\nComments:", item['data']['num_comments']) print("----")##print formated#print (json.dumps(cont, indent=4, sort_keys=True))print("Number of titles: ", counter)
output will be like this one:
...Title: Maybe we shouldn't let grandma decide things anymore. Comments: 2018---- Title: Carrie Fisher and Her Stunt Double Sunbathing on the Set of Return of The Jedi, 1982 Comments: 880---- Title: fidget spinner Comments: 1537---- Number of titles: 25
I would usually use the requests
package with the json
package. The following code should be suitable for your needs:
import requestsimport jsonurl = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'r = requests.get(url)print(json.loads(r.content))
Output
[11008076, 11006915, 11008202, ...., 10997668, 10999859, 11001695]