0

Ive a json file,

{
    "IGCSE":[
        {
            "rolename": "igcsesubject1",
            "roleid": 764106550863462431
        },
        {
            "rolename": "igcsesubject2",
            "roleid": 764106550863462431
        }
    ],
    "AS":[
        {
            "rolename": "assubject1",
            "roleid": 854789476987546
        },
        {
            "rolename": "assubject2",
            "roleid": 854789476987546
        }
    ],
    "A2":[
        {
            "rolename": "a2subject1",
            "roleid": 854789476987856
            
        },
        {
            "rolename": "a2subject2",
            "roleid": 854789476987856
        }
    ]

}

I want to fetch the keys [igcse, as, a2..] and then fetch the rolename and roleids under the specific keys. How do i do it? Below is the python code for how i used to do it without the keys.

with open(fileloc) as f:
    data = json.load(f)
    for s in range(len(data)):
        d1 = data[s]
        rname = d1["rolename"]
        rid = d1["roleid"]


any help would be appreciated :)

Ashhar Amir
  • 38
  • 3
  • 9
  • After you load the json in python it becomes a dict. Look into how python iterates over dictionaries. https://stackoverflow.com/a/3294899/4983469 – leoOrion Oct 28 '20 at 15:49

3 Answers3

0

First you can have a list of keys, under which you will get them:

l = ['A1','A2']

Then iterate like this:

for x in data:
  if x in l:
    for y in range(len(data[x])):
      print(j[x][y]['rolename'])
      print(j[x][y]['roleid'])
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

hi you can use for and you will get the keys:

with open(fileloc) as f:
data = json.load(f)
for s in data:
    d1 = data[s]
    rname = d1["rolename"]
    rid = d1["roleid"]
0

The following would work for what you need:

with open(file) as f:
    json_dict = json.load(f)
    for key in json_dict:
        value_list = json_dict[key]
        for item in value_list:
            rname = item["rolename"]
            rid = item["roleid"]

If you need to filter for specific keys in the JSON, you can have a list of keys you want to obtain and filter for those keys as you iterate through the keys (similar to Wasif Hasan's suggestion above).