Search code examples
pythonurllib

How to return JSON format from urlopen() response?


I am newbie to python and when trying such a code, I got weird characters.

import json
from urllib.request import urlopen

with urlopen(
        "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=MSFT&region=1&lang=en") \
            as response:
    source = response.read()
    print(source)

I expect the response to be JSON format but I got weird response like this:

enter image description here


Solution

  • I got the expected output using the following with requests:

    import requests
    
    url = 'http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=MSFT&region=1&lang=en'
    
    rsp = requests.get(url)
    print(rsp.json())