我正在尝试使用postcode.io通过它们在网站https://postcodes.io/上显示的“批量查找邮政编码”来从一堆邮政编码中获取经度和纬度。
我正在尝试将json对象传递到api点,如文档中所示,但始终收到标题中显示的错误。
这是我的代码;
allpostcodes = [i['postcode'] for i in _sortedstores()] # Getting postcodes from json file
data = {}
data['postcodes'] = allpostcodes # creating a dictionary and keeping `postcodes` and key and the postcode's as the value as shown in the example
_postcodearray = 'https://api.postcodes.io/%s' % json.dumps(data) # creating a json object and passing in the data
#_postcodearray = 'https://api.postcodes.io/%s' % data['postcodes'] #Not working
try:
with urllib.request.urlopen(_postcodearray) as _postcodearray:
a = _postcodearray.read()
a = json.loads(a.decode('utf-8'))
print(a)
except Exception as e:
print(e)
在我对它使用json.dump之前,数据变量的外观{'postcodes': ['GU34 2QS', 'TN23 7DH', 'HP20 1DH']}
我也试图定期传递导致相同错误的数组。对于我可能做错的任何帮助/建议,将不胜感激。
答案 0 :(得分:2)
#!/usr/bin/env python3
import json
import urllib.request
allpostcodes = ["OX49 5NU", "M32 0JG", "NE30 1DP"]
#allpostcodes = [i['postcode'] for i in sortedstores] # Getting postcodes from json file
values = {}
# creating a dictionary and keeping `postcodes` and key and
# the postcode's as the value as shown in the example
values['postcodes'] = allpostcodes
api_endpoint = 'https://api.postcodes.io/postcodes/'
data = json.dumps(values).encode('utf8')
req = urllib.request.Request(api_endpoint, data,
headers={'content-type': 'application/json'})
try:
with urllib.request.urlopen(req) as response:
result = json.loads(response.read())
print(json.dumps(result, indent=2))
except Exception as e:
print(e)