Link to home
Start Free TrialLog in
Avatar of crompnk
crompnkFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Extract decimal from dictionary object of json data

When extracting data from a dictionary object of json data I get the following error, it doesn't like the floating number i.e. 1.6, it just extracts integers. How do I adjust the script to parse the decimals.

Traceback (most recent call last):
  File "N:/Configuration/MetOfficehourlyjson test.py", line 30, in <module>
    Temperature = int((FCData_Dic['SiteRep']['DV']['Location']['Period'][0]['Rep'][0]['T']))
ValueError: invalid literal for int() with base 10: '1.6'


import urllib.request
import json

###  THIS IS THE CALL TO GET THE MET OFFICE FILE FROM THE INTERNET
response = urllib.request.urlopen('http://datapoint.metoffice.gov.uk/public/data/val/wxobs/all/json/3002?res=hourly&key=****API Key****')
FCData = response.read()
FCDataStr = FCData.decode('utf-8')
###   END OF THE CALL TO GET MET OFFICE FILE FROM THE INTERNET

#Converts JSON data to a dictionary object
FCData_Dic = json.loads(FCDataStr)

#The following are examples of extracting data from the dictionary object.
#The JSON data is heavily nested.
#Each [] goes one level down, usually defined with {} in the JSON data.
dataDate = (FCData_Dic['SiteRep']['DV']['dataDate'])
print('dataDate =',dataDate)

#There are also [] in the JSON data, which are referenced with integers, 
# starting from [0]
#Here, the [0] refers to the first day's block of data defined with [].
DateDay0 = (FCData_Dic['SiteRep']['DV']['Location']['Period'][0]['value'])
print('DateDay0 =',DateDay0)

#The second [0] picks out each of the first day's forecast data, in this case the time, referenced by '$'
TimeOfFC = (FCData_Dic['SiteRep']['DV']['Location']['Period'][0]['Rep'][0]['$'])
print('TimeOfFC =',TimeOfFC)

#Ditto for the temperature.    
Temperature = int((FCData_Dic['SiteRep']['DV']['Location']['Period'][0]['Rep'][0]['T']))
print('Temperature =',Temperature)

#Ditto for the screen relative humidity.    
#ScreenRelativeHumidity = int((FCData_Dic['SiteRep']['DV']['Location']['Period'][0]['Rep'][0]['H']))
#print('ScreenRelativeHumidity =',ScreenRelativeHumidity)

#Ditto for the weather Type (a code number).
#WeatherType = int((FCData_Dic['SiteRep']['DV']['Location']['Period'][0]['Rep'][0]['W']))
#print('WeatherType =',WeatherType)

#Ditto for the wind gust (a code number).
#WindGust = int((FCData_Dic['SiteRep']['DV']['Location']['Period'][0]['Rep'][0]['G']))
#print('WindGust =',WindGust)

#Ditto for the pressure.    
#Pressure = int((FCData_Dic['SiteRep']['DV']['Location']['Period'][0]['Rep'][0]['P']))
#print('Pressure =',Pressure)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Mark Brady
Mark Brady
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial