Python错误加载谷歌API的JSON代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34573197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:11:52  来源:igfitidea点击:

Python error load JSON code of google API

pythonjsongoogle-geocoding-api

提问by Gavin

I am using google geocode API to test the following Python code using Python 3.5. But receive the error below. The code is copied from sample code of Coursera. We suppose to be able to test any locations. For example: Ann Arbor, MI

我正在使用 google geocode API 使用 Python 3.5 测试以下 Python 代码。但是收到下面的错误。代码复制自Coursera的示例代码。我们假设能够测试任何位置。例如:密歇根州安娜堡

Any idea about why I have the error when load JSON code:

关于为什么我在加载 JSON 代码时出现错误的任何想法:

raise JSONDecodeError("Expecting value", s, err.value) from None >JSONDecodeError: Expecting value

引发 JSONDecodeError("Expecting value", s, err.value) from None >JSONDecodeError: Expecting value

here are the codes:

这里是代码:

import urllib
import json

serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?'

while True:
    address = input('Enter location: ')
    if len(address) < 1 : break

    url = serviceurl + urllib.parse.urlencode({'sensor':'false',
       'address': address})
    print ('Retrieving', url)
    uh = urllib.request.urlopen(url)
    data = uh.read()
    print ('Retrieved',len(data),'characters')

    js = json.loads(str(data))

采纳答案by nshiff

So, I had to modify your code to run. I am using Python 3.4.3 on Ubuntu 14.04.

所以,我不得不修改你的代码才能运行。我在 Ubuntu 14.04 上使用 Python 3.4.3。

#import urllib  
import urllib.parse
import urllib.request

I received a similar error:

我收到了类似的错误:

heyandy889@laptop:~/src/test$ python3 help.py 
Enter location: MI
Retrieving http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=MI
Retrieved 1405 characters
Traceback (most recent call last):
  File "help.py", line 18, in <module>
    js = json.loads(str(data))
  File "/usr/lib/python3.4/json/__init__.py", line 318, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.4/json/decoder.py", line 343, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.4/json/decoder.py", line 361, in raw_decode
    raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)

Basically, instead of trying to decode the valid json string, we're trying to decode the Python 'None' value, which is not valid json. Try patching in the following example code. Run it first once to double-check that the simplest json object '{}' will work. Then, try each different 'possible_json_string' one by one.

基本上,我们不是尝试解码有效的 json 字符串,而是尝试解码 Python 'None' 值,它不是有效的 json。尝试在以下示例代码中打补丁。首先运行一次以仔细检查最简单的 json 对象“{}”是否可以工作。然后,一个一个地尝试每个不同的 'possible_json_string'。

#...
print ('Retrieved',len(data),'characters')

#possible_json_string = str(data) #original error
possible_json_string = '{}' #sanity check with simplest json
#possible_json_string = data #why convert to string at all?
#possible_json_string = data.decode('utf-8') #intentional conversion

print('possible_json_string')
print(possible_json_string)
js = json.loads(possible_json_string)

Source

来源

回答by Sam Chan

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

出现错误是因为“数据”是字节类型,因此您必须在json.loads将其转换为 json 对象之前将其解码为字符串。所以要解决这个问题:

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.

此外,您共享的代码中的 str(data) 可以在 Python 2.x 中使用,但不能在 Python 3.x 中使用,因为 str() 不会将字节转换为 3.x 中的字符串。

回答by 7r4c0r

Look at the error:

看错误:

"raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting value"

"raise JSONDecodeError("Expecting value", s, err.value) 从 None

JSONDecodeError: 期望值"

It's saying I got a None when I was supposed to get something.

它是说当我应该得到一些东西时我得到了一个 None 。

Check your data variable for None before calling the json.loads().

在调用json.loads().

if data == None or data == '':
  print('I got a null or empty string value for data in a file')
else:
  js = json.loads(str(data))