I want to be able to iterate with the dictionary from Json that like how it is done with list.
import json f = ''' { "configurator": { "term": "enabled" }, "monitor": { "nortel": "thread" }, "micros": { "code": "1200" }, "universities": { "univ1": { "code": "TTSG", "rsample": { "meta_data": "TGED", "samcode": "" }, "tables": { "count": "1" }, "storage": { "wooden": [], "metal": [], "plastic": [] } }, "univ2": { "code": "TTSS", "rsample": { "meta_data": "TGES", "samcode": "" }, "tables": { "count": "2" }, "storage": { "wooden": [], "metal": [], "plastic": [] } } } } ''' data = json.loads(f) data_topology = data['universities'] for item in data_topology: print(item.rsample)
Getting below error.
Traceback (most recent call last): File "main.py", line 52, in <module> print(item.rsample) AttributeError: 'str' object has no attribute 'rsample' ** Process exited - Return Code: 1 ** Press Enter to exit terminal
Expected:
Should be able to use any of the key values inside for loop to iterate for each of the univ# block. ie., each univ# should a an item in for loop so that I can perform some actions on any number of univ#
Advertisement
Answer
The json object is actually a dictionary, so instead of
for item in data_topology: print(item.rsample)
You have write:
for key in data_topology: print(data_topology[key])
Or even better:
for key, value in data_topology.items(): print(key, ":", value)