checking value on json - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: checking value on json (/thread-23771.html) |
checking value on json - enigma619 - Jan-16-2020 Hi i've a little question about checking a value in a json file. I've my json file like that: { "server_model": { "server_type1": { "service":["service1","service2"], "seuil":{} }, "server_type2": { "service":["service1","service2"], "seuil":{} }, } }In my python script I want to check if a value exist in my json file, and it not, error message and exist. So i use: server_type = "server_type2" try: data_config = json.load(json_file) except ValueError: logging.critical("Data were not valid json for %s", data_config) sys.exit(1) for key, value in data_config.items(): if server_type not in data_config: logging.critical("We can not continue: Server type %s not present in config file", server_type) sys.exit(50)But it doesnt work. My result is that script go on this logging.critical. (If I put if server_type in data_config, it works but it's not logical..) I tried many things to parse this value but with no success... I spent many time on this little problem so if you have ideas... ? Thanks for light Alex RE: checking value on json - buran - Jan-16-2020 not tested but try: server_type = "server_type2" try: data_config = json.load(json_file) except ValueError: logging.critical("Data were not valid json for %s", data_config) else: if server_type not in data_config['server_model'].keys(): logging.critical("We can not continue: Server type %s not present in config file", server_type)depending on what you would do further it may be better to try to access data you want with data_config['server_model'].get(server_type) and act accordingly from there
RE: checking value on json - enigma619 - Jan-16-2020 Top it works fine. Thanks for answer, I understand now. Alex |