Iterate over Json with no list in python

Question:

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#

Asked By: youhoome

||

Answers:

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)
Answered By: Florin C.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.