i wrote an little algorithm that iterates over a dictionary and then over a json file with the goal to replace specific keys.
I have three items in the dictionary that should be replaced. The problem is that the function only replaces the first entry from the dictionary and not the other ones but the foor loop is iterated three times, like it should.
I think its a logical error but i dont find it.
class Replacer:
def __init__(self, form_json_path: str, replace_dict: dict):
self.file_read = open (f'{form_json_path}', 'r')
self.file_path = form_json_path
self.replace_dict = replace_dict
def replace_keys(self):
replaced_json = ''
for before, after in self.replace_dict.items():
search_phrase = f'"key":"{before}"'
additional_search_phrase = f'"key": "{before}"'
for line in self.file_read:
if (search_phrase in line or additional_search_phrase in line):
replaced_json_line = line.replace(f'{before}', f'{after}')
replaced_json += replaced_json_line
else:
replaced_json += line
print(replaced_json)
self.file_read.close()
keys_to_replace = {
"antragsumfang_Panel": "antragsumfang_PanelREPLACED",
"antragsumfangHinweis_HTMLElement": "antragsumfangHinweis_HTMLElementREPLACED",
"antragsumfangHinweisZwei_HTMLElement": "antragsumfangHinweisZwei_HTMLElementREPLACED"
}
f = Replacer('t.json', keys_to_replace)
f.replace_keys()
>Solution :
The issue lies in the inner loop. Files objects do not automatically go back to the beginning of the file when they reach the end. The first time, it iterates over the lines as it should but the second and third times it does nothing because it is already at the end.
To fix this add self.file_read.seek(0) after the inner loop to go back to the beginning of the file.