TAB_SIZE = 2 tab = 0 tabArray = 0 result = '{\n' brackets = [] def append_to_result(string): global result, tab result += f'{" " * (tabArray + tab + 2)}{string}' with open('input.yaml', encoding='UTF-8') as inpt: inpt = inpt.readlines() for key, i in enumerate(inpt): i = i.split(':') if tab != len(i[0]) - len(i[0].lstrip()): if tab < len(i[0]) - len(i[0].lstrip()): tab = len(i[0]) - len(i[0].lstrip()) else: tab = len(i[0]) - len(i[0].lstrip()) result = result[:len(result) - 2] + '\n' append_to_result(brackets.pop() + ',\n') if i[0].strip()[0] == '-': if tab == tabArray and ']' not in brackets: append_to_result('[\n') brackets.append(']') tabArray += 2 i[0] = i[0].lstrip()[1:].strip() append_to_result('{\n') brackets.append('}') tab += TAB_SIZE if i[1].strip() == '': br = '' if inpt[key+1].split(':')[0].strip()[0] == '-': br = '[]' else: br = '{}' append_to_result(f'"{i[0].strip()}": {br[0]}\n') brackets.append(br[1]) else: def shielding(s: str): return s.replace("\\", "\\\\").replace("\"", "\\\"") i = list(map(shielding, i)) append_to_result(f'"{i[0].strip()}": "{":".join(i[1:]).strip()}",\n') if brackets is not None: for _ in range(len(brackets)): tab -= TAB_SIZE result = result[:len(result) - 2] + '\n' i = brackets.pop() append_to_result(i + ',\n') result = result[:len(result) - 2] + '\n' result += '}' with open('output.json', 'w', encoding='UTF-8') as output: output.write(result) print(result)