跳至主要内容

博文

目前显示的是 三月, 2021的博文

Working with case insensitive Json in python

We want the json keys to be case-insensitive Okay, I hope this is not your case, as it is too weird to work this way. But If you have to. Or, If you must to. Solution is to: Just working in a specific case, upper or lower, and blindly convert all data to that case. To do this in Python, when you load a JSON file/string you can define a hook named object_pairs_hook as below: import pathlib my_file = pathlib.Path.cwd().join( 'my_example.json' ) def lower_case_keys (tuple_list): return dict ([(k.lower(), v) for k, v in tuple_list]) json.loads(my_file.read_text(encoding= 'UTF-8' ), object_pairs_hook=lower_case_keys) From here on, all your json operation should be using lower-cased keys.