Python 3 Get and parse JSON API

前端 未结 5 1172
醉梦人生
醉梦人生 2021-01-31 14:58

How would I parse a json api response with python? I currently have this:

import urllib.request
import json

url = \'https://hacker-news.firebaseio.com/v0/topsto         


        
5条回答
  •  迷失自我
    2021-01-31 15:27

    you can use standard library python3:

    import urllib.request
    import json
    url = 'http://www.reddit.com/r/all/top/.json'
    req = urllib.request.Request(url)
    
    ##parsing response
    r = urllib.request.urlopen(req).read()
    cont = json.loads(r.decode('utf-8'))
    counter = 0
    
    ##parcing json
    for 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
    

提交回复
热议问题