Good afternoon!
I am attempting to write a script where some configurations can be made on machines, based on a JSON file passed into it. The JSON file is loaded into a variable, and that variable is a dictionary. That dictionary contains other dictionaries and lists of dictionaries. So my question is, even though I know the structure of the dictionary due to the JSON file, how do I use the keys/values when I don’t know what either is going to be? I only know the structure.
For example:
{
"Product": "My_Application",
"Version": "1.0",
"Locations": [
{"Atlanta": [
{"Server_1": [
{"hostname": "ATLhost1},
{"ip_address": "10.10.10.10"},
{"widget_dir": "/opt/myApp/widget_logs"},
{"app_type" : "log server"},
{"log_directories": [
{"access_logs: "/opt/myApp/widget_logs/access"},
{"error_logs: "/opt/myApp/widget_logs/error"},
{"debug_logs: "/opt/myApp/widget_logs/debug"}
]}
]},
{"Server_2": [
{"hostname": "ATLhost2},
{"ip_address": "10.10.10.11"},
{"widget_dir": "/opt/myApp/widget_web"},
{"app_type" : "web server"}
]}
]},
{"Baltimore": [
{"Server_1": [
{"hostname": "BLThost1},
{"ip_address": "10.10.20.10"},
{"widget_dir": "/opt/myApp/widget_logs"},
{"app_type" : "log_server"},
{"log_directories": [
{"access_logs: "/opt/myApp/widget_logs/access"},
{"error_logs: "/opt/myApp/widget_logs/error"},
{"debug_logs: "/opt/myApp/widget_logs/debug"}
]},
{"Server_2": [
{"hostname": "BLThost2},
{"ip_address": "10.10.20.11"},
{"widget_dir": "/opt/myApp/widget_web"},
{"app_type" : "web server"}
]}
]}
]
}
Once this is loaded from JSON, how would I access [Locations][0][Baltimore][0][log_directories][0][error_logs] when I don’t know that the location name is going to be ‘Baltimore’? Could “Baltimore” be wildcarded somehow? I am trying desperately to make this script dynamic, so that it can be run on any machine in any location. In order to do that, however, I have to figure out how to access this data without knowing what some of the data will be. I definitely do not want end-users having to edit the script in order to be able to run it.
I have attempted to use loops and if statements to accomplish what I need to, but I am ending up with a lot of nested for loops and if/else conditions, which is making readability… suboptimal. I’m hoping someone smarter than me can suggest a better way, so that someone editing this thing after me will not need a bottle of Excedrin to get through it.
Thank you!
pythonic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.