Python error load JSON code of google API

后端 未结 3 1433
闹比i
闹比i 2020-12-11 16:24

I am using google geocode API to test the following Python3.5 code but receive the error below.

raise JSONDecodeError("Expecting value", s, err

3条回答
  •  一整个雨季
    2020-12-11 17:11

    The error arises because the "data" is of type bytes so you have to decode it into a string before using json.loads to turn it into a json object. So to solve the problem:

    uh = urllib.request.urlopen(url)
    data = uh.read()
    print ('Retrieved',len(data),'characters')
    
    js = json.loads(data.decode("utf-8"))
    

    Also, str(data) in the code you share will work in Python 2.x but not in Python 3.x because str() doesn't turn bytes into a string in 3.x.

提交回复
热议问题