I made this program to rename variables in json files, part of the functions rely on recursivity which i'm not confortable with so I would like some feedback on readability and performance.
import configparser
def seek_in_array(json_array, conversions):
"""seeks all data in a json array"""
converted = []
for it_list in range(len(json_array)):
if isinstance(json_array[it_list], dict):
converted.append(seek_and_convert(json_array[it_list], conversions))
elif isinstance(json_array[it_list], list):
converted.append(seek_in_array(json_array[it_list], conversions))
else:
converted.append(json_array[it_list])
return(converted)
def seek_and_convert(json_file, conversions):
"""seeks all data in a json file an converts it"""
converted = {}
for key in json_file.keys():
if conversions.has_option('CONVERSIONS', key):
option = conversions.get('CONVERSIONS', key)
else:
option = key
if isinstance(json_file[key], dict):
converted[option] = seek_and_convert(json_file[key], conversions)
elif isinstance(json_file[key], list):
converted[option] = seek_in_array(json_file[key], conversions)
else:
converted[option] = json_file[key]
return(converted)
def load_conversion_table():
"""loads the configfile containing the conversions to be made"""
conversions = configparser.ConfigParser()
conversions.read('conversion_table.ini')
return conversions
def main():
conversions = load_conversion_table()
file = {
'_id': '006480206',
'change1': 'HEY'
'A_THING': 'HEY'
'an_array': [
{
'A_THING_in_the_array': '00648020600017',
'oh_no_,_change_that':'O',
'plz_dont_change_me': '12',
'listenning_to_disco_music': True,
'le_list': {
'le_variable': 'baguette !',
'le_change': 42,
},
"that's a trap": {},
"change_it_anyway": {},
'another_array': [
{
'change1': 'HANS !',
'change2': 'JA !?'
},
{
'nei': 'yas'
'change1': 'the very test',
},
{
'change1': 'ran out of idea',
'yas_yas': 'nomnomnom'
},
{
'OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOH': 'such long name'
}
]
}
]
}
print(seek_and_convert(file, conversions))
if __name__ == "__main__":
main()
Here is the config file you'll need to run the program, put both file in the same folder.
conversion_table.ini:
[CONVERSIONS]
change1 = success1
oh_no_,_change_that = oh_no_,_success_that
plz_dont_change_me = plz_dont_success_me
le_change = le_success
change_it_anyway = success_it_anyway
change2 = success2