Python 读取 met.no 天气 API 在尝试转换为 JSON 时提供"string indices must be integers"



我正在阅读。没有天气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库的文档

相关内容

  • 没有找到相关文章

最新更新