Advertisement
Guest User

Untitled

a guest
Nov 17th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. import json
  2.  
  3.  
  4. def open_file(path_to_file):
  5.     return open(path_to_file)
  6.  
  7.  
  8. def parse(file):
  9.     line_inner = 0
  10.     json_data = {}
  11.     last_header = None
  12.     main_header = None
  13.     under_header = None
  14.     # Lines
  15.     for line in file.readlines():
  16.         # Line
  17.         for s in line:
  18.             if s == ' ':
  19.                 line_inner += 1
  20.             else:
  21.                 break
  22.  
  23.         data = line[line_inner:]
  24.         # HEADER
  25.         if len(data.split(' ')) == 1:
  26.             if line_inner == 0:
  27.                 main_header = data[:-2]
  28.                 json_data[data[:-2]] = {}
  29.             elif line_inner == 2:
  30.                 under_header = data[:-2]
  31.                 json_data[main_header][data[:-2]] = {}
  32.             else:
  33.                 last_header = data[:-2]
  34.                 json_data[main_header][under_header][data[:-2]] = {}
  35.  
  36.  
  37.         # DATA
  38.         else:
  39.             key = data.split(':')[0]
  40.             if len(data.split(':')[1]) <= 2:
  41.                 json_data[main_header][under_header][last_header][key] = ''
  42.             else:
  43.                 value = ''.join(data.split(':')[1:])[2:-2]
  44.                 new_value = data.split(':', maxsplit=1)[1].replace('"', '')[1:-1]
  45.                 json_data[main_header][under_header][last_header][key] = new_value
  46.  
  47.         line_inner = 0
  48.  
  49.     with open('data.json', 'w', encoding='utf-8') as file:
  50.         iter = 0
  51.         for k, v in json_data.items():
  52.             if iter == 0:
  53.                 k = '{}'.format(k)
  54.                 k = "{'" + k + "'"
  55.                 iter+=1
  56.             file.write('{}:{}\n'.format(k.replace("'", '"'), str(v).replace("'", '"')))
  57.         file.write('}')
  58.  
  59. parse(open_file('data.yml'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement