我正在阅读。没有天气API从URL https://api.met.no/weatherapi/locationforecast/2.0/complete?lat=59.911491&lon=10.757933
import json
from urllib.request import Request, urlopen
# Read forecast
url = "https://api.met.no/weatherapi/locationforecast/2.0/complete?lat=59.911491&lon=10.757933"
req = Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:101.0) Python/3.10.5')
content: bytes = urlopen(req).read()
# Convert to JSON
json_str: str = content.decode('utf8').replace("'", '"')
json_data = json.load(json_str)
# Print data
type = json_data["type"]
print(f"{type}")
这给了我错误AttributeError: 'str' object has no attribute 'load'
。
有一个小错别字。你应该用json.loads
而不是json.load
。
import json
from urllib.request import Request, urlopen
# Read forecast
url = "https://api.met.no/weatherapi/locationforecast/2.0/complete?lat=59.911491&lon=10.757933"
req = Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:101.0) Python/3.10.5')
content: bytes = urlopen(req).read()
# Convert to JSON
json_str: str = content.decode('utf8').replace("'", '"')
json_data = json.loads(json_str)
# Print data
type = json_data["type"]
print(f"{type}")
输出:
Feature
方法json.load
期望一个IO流作为参数,但是您正在给出一个字符串。尝试json.loads
方法查看json库的文档