Python urllib2: Receive JSON response from url

后端 未结 10 1868
轮回少年
轮回少年 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 17:54
    resource_url = 'http://localhost:8080/service/'
    response = json.loads(urllib2.urlopen(resource_url).read())
    
    0 讨论(0)
  • 2020-11-29 17:57

    Though I guess it has already answered I would like to add my little bit in this

    import json
    import urllib2
    class Website(object):
        def __init__(self,name):
            self.name = name 
        def dump(self):
         self.data= urllib2.urlopen(self.name)
         return self.data
    
        def convJSON(self):
             data=  json.load(self.dump())
         print data
    
    domain = Website("https://example.com")
    domain.convJSON()
    

    Note : object passed to json.load() should support .read() , therefore urllib2.urlopen(self.name).read() would not work . Doamin passed should be provided with protocol in this case http

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

    Python 3 standard library one-liner:

    load(urlopen(url))
    
    # imports (place these above the code before running it)
    from json import load
    from urllib.request import urlopen
    url = 'https://jsonplaceholder.typicode.com/todos/1'
    
    0 讨论(0)
  • 2020-11-29 18:04
    """
    Return JSON to webpage
    Adding to wonderful answer by @Sanal
    For Django 3.4
    Adding a working url that returns a json (Source: http://www.jsontest.com/#echo)
    """
    
    import json
    import urllib
    
    url = 'http://echo.jsontest.com/insert-key-here/insert-value-here/key/value'
    respons = urllib.request.urlopen(url)
    data = json.loads(respons.read().decode(respons.info().get_param('charset') or 'utf-8'))
    return HttpResponse(json.dumps(data), content_type="application/json")
    
    0 讨论(0)
  • 2020-11-29 18:04

    Be careful about the validation and etc, but the straight solution is this:

    import json
    the_dict = json.load(response)
    
    0 讨论(0)
  • 2020-11-29 18:07

    None of the provided examples on here worked for me. They were either for Python 2 (uurllib2) or those for Python 3 return the error "ImportError: No module named request". I google the error message and it apparently requires me to install a the module - which is obviously unacceptable for such a simple task.

    This code worked for me:

    import json,urllib
    data = urllib.urlopen("https://api.github.com/users?since=0").read()
    d = json.loads(data)
    print (d)
    
    0 讨论(0)
提交回复
热议问题