Untitled

 avatar
unknown
python
2 years ago
2.9 kB
7
Indexable
cbrace_counter = 0
nbrace_counter = 0
sbrace_counter = 0
stack = ['', '']


def linefeed_checker(line, flag, yaml_file):
    global cbrace_counter, nbrace_counter, sbrace_counter, stack
    # yaml_file1 = open('D:/Sublime Text/Projects/YAML_file#1.yaml', 'w')
    if line != (' ' * len(line)) and line[-2:] != '- ':
        if '\":' in line:
            line = line.replace('\"', '', 2)
        yaml_file.write(line + '\n')
    if stack[-1] == '[' or (stack[-2] == '[' and stack[-1] == '{' and flag):
        line = '  ' * (cbrace_counter + sbrace_counter - 1) + '- '
    else:
        line = '  ' * (cbrace_counter + sbrace_counter)
    # yaml_file1.close()
    return line


def converter(path_to_json, path_to_yaml):
    json_file = open(path_to_json, 'r')
    # json_file = json_file.readlines()[1:-1]
    yaml_file = open(path_to_yaml, 'w')
    text = ''
    for line in json_file.readlines()[1:-1]:  # Убираем ненужную табуляцию
        ind1 = 0
        while line[ind1] == ' ':
            ind1 += 1
        ind2 = len(line) - 2
        while line[ind2] == ' ':
            ind2 -= 1
        text += line[ind1:ind2 + 1]
    global cbrace_counter, nbrace_counter, sbrace_counter, stack
    line = ''
    # print(file)
    for ch in text:
        if ch == '{':
            stack.append('{')
            if stack[-2] != '[':
                cbrace_counter += 1
                line = linefeed_checker(line, False, yaml_file)
            else:
                line = linefeed_checker(line, True, yaml_file)
        elif ch == '}':
            if stack[-2] != '[':
                cbrace_counter -= 1
            stack.pop()
            line = linefeed_checker(line, False, yaml_file)
        elif ch == '[':
            sbrace_counter += 1
            stack.append('[')
            line = linefeed_checker(line, False, yaml_file)
        elif ch == ']':
            sbrace_counter -= 1
            stack.pop()
            line = linefeed_checker(line, False, yaml_file)
        elif ch == ',':
            if '\\n' in line:
                # print(line)
                d = '|'
                # print(line[-2:])
                if line[-2:] != 'n\"':
                    d += '-'
                else:
                    line = line[:len(line) - 3] + '\"'
                line = line.replace(':', f': {d}\n ', 1)
                line = line.replace('\\n', f'\n  {"  " * (cbrace_counter + sbrace_counter)}')
                line = line.replace('\"', '')
                # print(line)
            line = linefeed_checker(line, False, yaml_file)
        else:
            line += ch
    linefeed_checker(line, False, yaml_file)
    json_file.close()
    yaml_file.close()
    cbrace_counter = 0
    nbrace_counter = 0
    sbrace_counter = 0
    stack = ['', '']
Editor is loading...
Leave a Comment