heildever heildever - 13 days ago 6
JSON Question

Parsing a JSON dictionary with unknown values

I am trying to deal with a dictionary in JSON, looks like following:

{
"Parameters": {
"IP": "192.168.1.40",
"TIMEOUT": 900,
"mode": 0
},

"Device": {
"sector01": {
"nodes": ["node01", "node02"]
},
"sector02": {
"nodes": ["node01"]
},
"sector03": {
"nodes": ["node01","node02","node03"]
}
}
}


Assume I have no info about the how many sectors and nodes are present and I want to know the number of sectors (and how many nodes per sector).
I was able to find the total no of sectors by :

len(data["Device"])


But, the total no of nodes per sector is more important in my case.

Answer

You can use for-loop to get every "sector" (it doesn't matter how many you have sectors) and then you can get "nodes" in sector and check len()

for key, val in data['Device'].items(): 
    print(key, len(val["nodes"]))
Comments