I want to be able to iterate with the dictionary from Json that like how it is done with list.
JavaScript
x
53
53
1
import json
2
3
f = '''
4
{
5
"configurator": {
6
"term": "enabled"
7
},
8
"monitor": {
9
"nortel": "thread"
10
},
11
"micros": {
12
"code": "1200"
13
},
14
"universities": {
15
"univ1": {
16
"code": "TTSG",
17
"rsample": {
18
"meta_data": "TGED",
19
"samcode": ""
20
},
21
"tables": {
22
"count": "1"
23
},
24
"storage": {
25
"wooden": [],
26
"metal": [],
27
"plastic": []
28
}
29
},
30
"univ2": {
31
"code": "TTSS",
32
"rsample": {
33
"meta_data": "TGES",
34
"samcode": ""
35
},
36
"tables": {
37
"count": "2"
38
},
39
"storage": {
40
"wooden": [],
41
"metal": [],
42
"plastic": []
43
}
44
}
45
}
46
}
47
'''
48
data = json.loads(f)
49
data_topology = data['universities']
50
51
for item in data_topology:
52
print(item.rsample)
53
Getting below error.
JavaScript
1
9
1
Traceback (most recent call last):
2
File "main.py", line 52, in <module>
3
print(item.rsample)
4
AttributeError: 'str' object has no attribute 'rsample'
5
6
7
** Process exited - Return Code: 1 **
8
Press Enter to exit terminal
9
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
JavaScript
1
3
1
for item in data_topology:
2
print(item.rsample)
3
You have write:
JavaScript
1
3
1
for key in data_topology:
2
print(data_topology[key])
3
Or even better:
JavaScript
1
3
1
for key, value in data_topology.items():
2
print(key, ":", value)
3