I have the next data:
{
"AlignedDataCtrlr": {
"Enabled": false,
"Measurands": {
"readOnly": false,
"value": []
},
"Interval": {
"readOnly": false,
"value": 50,
"unit": "seconds"
},
"TxEndedMeasurands": {
"readOnly": false,
"value": []
},
"TxEndedInterval": {
"readOnly": true,
"value": 50,
"unit": "seconds"
}
},
"AuthCacheCtrlr": {
"Enabled": false,
"AuthCacheEnabled": {
"readOnly": false,
"value": true
},
"AuthCacheLifeTime": {
"readOnly": true,
"value": true
}
},
...
}
And I want to print every variable that is not read only, for example print Measurands and its values, Interval, etc...
I start with
import json
file = open("./configs/configuration.json")
config = json.load(file)
for each_ctrlr in config:
for each_key in each_ctrlr:
if 'readOnly' in each_key:
print(each_key)
But there's nothing printing...
CodePudding user response:
If you want to iterate through key-values at the same time, use .items()
If you just want to iterate over the key, use .keys()
If you just want to iterate over the values, use .values()
import json
with open("./configs/configuration.json", "r") as f:
config = json.load(f)
for k, v in config.items():
for k2, v2 in v.items():
if isinstance(v2, dict) and v2.get("readOnly"):
print(k2, v2)
Output
TxEndedInterval {'readOnly': True, 'value': 50, 'unit': 'seconds'}
AuthCacheLifeTime {'readOnly': True, 'value': True}