Pulling Data From JSON

I’m having some issues pulling data from a JSON object. The code is:

print receivedData
print DataJSON
for i in DataJSON["RoomTemp"]:
	print i["currentValue"]

The error I’m getting is regarding the print command in the for loop.

Traceback (most recent call last):
  File "<input>", line 6, in <module>
TypeError: unicode indices must be integers

My (simplified) outputs are:

print receivedData
		"current":"6.0 F",

print DataJSON
{u'RoomTemp': {u'units': 'F', u'current': '6.0 F', u'currentValue': '6.0'}}

Any help would be greatly appreciated.

In Python, iterating through a dictionary will get you the key names. You can then use these key names to get the values you’re looking for out of the dictionary.

Here’s one option:

DataJSON = {u'RoomTemp': {u'units': 'F', u'current': '6.0 F', u'currentValue': '6.0'}}
for key in DataJSON:
		print DataJSON[key]['currentValue']

And here’s another:

DataJSON = {u'RoomTemp': {u'units': 'F', u'current': '6.0 F', u'currentValue': '6.0'}}
for key in DataJSON:
	valueString = 'currentValue'
	currentValue = DataJSON[key][valueString] if valueString in DataJSON[key] else None
	print currentValue
1 Like

Yep, there are lots of options to iterate through dictionaries. You can go through just the values:

for room in DataJSON.values():
    print room["currentValue"]

Just the keys:

for key in DataJSON.keys(): #or leave the .keys() off entirely
    print DataJSON[key]["currentValue"]

Or both the key and value together:

for key, value in DataJSON.items():
     print key
     print value["currentValue"]

Thank you. This was extremely helpful.

The dictionary keys() method in Python returns a view object that displays a list of all the keys in the dictionary.

The dictionary values() method returns a view object. The view object contains the values of the dictionary, as a list. The view object will reflect any changes done to the dictionary.

The dictionary items() method is used to return the list with all dictionary keys with values.

These are the basic definitions of above answers.

I hope this helps,

1 Like