Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python reading met.no weather API gives "string indices must be integers" when trying to convert to JSON

I am reading met.no weather API from the 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}")

This gives me error AttributeError: 'str' object has no attribute 'load'.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There is a little typo mistake. You should use json.loads instead of 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}")

Output:

Feature
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading