Python urllib2: Receive JSON response from url

后端 未结 10 1869
轮回少年
轮回少年 2020-11-29 17:22

I am trying to GET a URL using Python and the response is JSON. However, when I run

import urllib2
response = urllib2.urlopen(\'https://api.instagram.com/v1/         


        
相关标签:
10条回答
  • 2020-11-29 18:11

    you can also get json by using requests as below:

    import requests
    
    r = requests.get('http://yoursite.com/your-json-pfile.json')
    json_response = r.json()
    
    0 讨论(0)
  • 2020-11-29 18:12
    import json
    import urllib
    
    url = 'http://example.com/file.json'
    r = urllib.request.urlopen(url)
    data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8'))
    print(data)
    

    urllib, for Python 3.4
    HTTPMessage, returned by r.info()

    0 讨论(0)
  • 2020-11-29 18:14

    If the URL is returning valid JSON-encoded data, use the json library to decode that:

    import urllib2
    import json
    
    response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
    data = json.load(response)   
    print data
    
    0 讨论(0)
  • 2020-11-29 18:15

    This is another simpler solution to your question

    pd.read_json(data)
    

    where data is the str output from the following code

    response = urlopen("https://data.nasa.gov/resource/y77d-th95.json")
    json_data = response.read().decode('utf-8', 'replace')
    
    0 讨论(0)
提交回复
热议问题