Pulling specific data from a json string

Hi folks,

I’m trying to add a UV index to my weather station, being a Pico W running MicroPython.

I can get the json data ok but I’m struggling to break out the UVI number, being the first UVI number in the json string.

Insights appreciated!

# 9/3/25 - UVI from https://currentuvindex.com/api

# v1 - Get the json data.
# v2 - Extract the uvi number

import urequests # Network Request Module
import json  # JSON handling module

# Define the API endpoint and your API key
api_url = "https://currentuvindex.com/api/v1/uvi?"
api_key = ""  # Replace with your actual API key

# Define the latitude and longitude for Caloundra as got from https://latlong.info/australia/queensland/caloundra
latitude = -26.80346000  
longitude = 153.12195000

# Construct the URL
request_url = f"{api_url}latitude={latitude}&longitude={longitude}"
print(request_url)

# Make the API request
response = urequests.get(request_url) # Send a GET request, the return type is the response of the request.

# Check if the request was successful
if response.status_code == 200:
    uvi_data = response.json()
    print("UVI Data:", uvi_data)
    print("Full UVI Data Response:")
    print(json.dumps(uvi_data))  # Print the entire JSON response.
    print(f'UVI: {uvi_data['uvi']}')
    
elif response.status_code == 400:
    print("Bad request. Please check your parameters and try again.")
elif response.status_code == 401:
    print("Unauthorized. Please check your API key.")
elif response.status_code == 404:
    print("Resource not found. Please check the URL.")
else:
    print("Failed to fetch UVI data. Status code:", response.status_code)

# Close the response to free up resources
response.close()




What is the json data that you are getting? What is the code you are using to convert the json data into a dictionary with the json.loads() method? That should return you a dictionary which you can use to lookup the UVI by label.

1 Like

Hi @Mark285907

In the past I’ve used this to get time and date data from http://date.jsontest.com. Rather than using the json library I used ujson.

def fetch_text_from_website(site):
    response = urequests.get(site)
    data = ujson.loads(response.text)
    response.close()
    return data['date'], data['time']

You should be able to change the last line to suit the information that you’re getting from the site,

2 Likes

After a lot of self education and reading between the lines of various web pages re json and assumed knowledge…I’ve got it working.

The goal was to get the current UVI value for my location.

Happy for someone to point me to more elegant coding for unraveling the json string (attached).

>>> %Run -c $EDITOR_CONTENT

MPY: soft reboot
URL response is https://currentuvindex.com/api/v1/uvi?latitude=-26.80346&longitude=153.1219
UVI Data:
UVI Now: {'time': '2025-03-10T05:00:00Z', 'uvi': 0.8}
UVI Now Number: 0.8
>>> 
import urequests # Network Request Module
import json
import ujson

# Define the API endpoint and your API key
api_url = "https://currentuvindex.com/api/v1/uvi?"
api_key = ""  # Replace with your actual API key

# Define the latitude and longitude for Caloundra as got from https://latlong.info/australia/queensland/caloundra
latitude = -26.80346000  
longitude = 153.12195000

# Construct the URL
request_url = f"{api_url}latitude={latitude}&longitude={longitude}"
print("URL response is " + request_url)

# Make the API request
response = urequests.get(request_url) # Send a GET request, the return type is the response of the request.

# Check if the request was successful
if response.status_code == 200:
    uvi_data = response.json() # Write the response to the variable.
    print("UVI Data:", uvi_data) # Print same for testing.
    print(f'UVI Now: {uvi_data['now']}') # Print the "now" array for testing.
    uvi_data_now = uvi_data['now'] # Get the "now" array.
    uvi_data_now_value = uvi_data_now['uvi'] # Get the "uvi" key value.
    print("UVI Now Number: " + str(uvi_data_now_value)) # Print the "now", "uvi" key value.
elif response.status_code == 400:
    print("Bad request. Please check your parameters and try again.")
elif response.status_code == 401:
    print("Unauthorized. Please check your API key.")
elif response.status_code == 404:
    print("Resource not found. Please check the URL.")
else:
    print("Failed to fetch UVI data. Status code:", response.status_code)

# Close the response to free up resources
response.close()

json.pdf (51.8 KB)

1 Like

Nice one! :partying_face:

1 Like