【发布时间】:2021-06-07 12:12:02
【问题描述】:
当我从 openweathermap 请求 json 时,字母 åäö (\xe4 \xe5 \xe6) 出现了一些问题。我该怎么做才能以正确的方式对其进行编码?
UnicodeEncodeError: 'ascii' codec can't encode character '\xe5' in position 27: ordinal not in range(128)
import json
from urllib.request import urlopen
def getSource(city, countrycode):
url = "http://api.openweathermap.org/data/2.5/weather?q={city},{countrycode}&appid=xxx".format(city=city, countrycode=countrycode)
with urlopen(url) as response:
source = response.read()
return(source)
source = getSource("Borås", "se")
data = json.loads(source)
print(json.dumps(data, indent=2))
【问题讨论】:
-
UnicodeEncodeError是否出现在json.loadsxorjson.dumps期间? -
是的。打印(json.dumps(数据,缩进=2))
标签: python openweathermap