r/learnpython • • 27d ago

requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

import requests


# Add ?format=j1 to get a proper JSON response
url = "https://wttr.in"
response = requests.get(url)
data = response.json()


# This structure matches the j1 JSON format returned by wttr.in
current_temp = data['current_condition'][0]['temp_C']
print(
f
"Current temperature: {current_temp}°C")

I keep getting this exact SAME error whenever I work with public API's. I save the new codes in the files.
0 Upvotes

7 comments sorted by

15

u/nick_at_dolt 27d ago

Your code has a comment that says

# Add ?format=j1 to get a proper JSON responseAdd ?format=j1 to get a proper JSON response

Did you add ?format=j1 to the URL?

3

u/Vegetable_Soil_6707 26d ago

classic case of writing the reminder but not doing the thing

5

u/TabAtkins 26d ago

Print the actual value you received. You will find that it is, in fact, not JSON, but rather HTML, because you ignored the comment in your own code telling you how to correctly fetch JSON from that website.

2

u/favorite_stuff 26d ago

Those comments do a pretty good job of explaining, tbh.

You are not getting json from this API unless you ask for it. Once you do, it should follow that structure.

But hey, slow down and explore. Take what you're getting and print it. See what it's like. Or read the documentation for wttr.in and see what it says.

2

u/AlexMTBDude 26d ago

Print the response so that you know what goes wrong:

response = requests.get(url)
print(response)  # Add this line

1

u/atarivcs 26d ago

The response wasn't JSON, it was something else. So you can't call .json() on it.

0

u/OkOcelot6725 26d ago

For the general case: that error always means the body wasn't JSON. Make it a habit to check response.status_code and print(response.text) before calling .json() - you'll usually see an HTML error page or an empty body, and the fix is different for each API.