today's your lucky day. This is quick and dirty, you should probably try to make it more efficient, but it works
You will also have to modify file names and paths
You will also have to modify file names and paths
from pathlib import Path import json class ParseData: def __init__(self): self.home = Path('.') self.datafile = self.home / 'data' / 'data.txt' self.dataout = self.home / 'data' / 'data.json' self.datadict = { } self.source = None self.rule = None self.dest = None newitem = False self.reading_source = False self.reading_destination = False self.alldata = [ ] with self.datafile.open() as f, self.dataout.open('w') as fo: line = f.readlines() for item in line: if item.startswith('Policy:'): if newitem: self.save_item() elements = item.split() self.rule = elements[1].strip(',') print(self.rule) self.datadict[self.rule] = { } newitem = True continue elif item.startswith('Source'): self.source = "sources" self.reading_source = True print('found source') self.datadict[self.rule]['sources'] = { } continue elif item.startswith('Destination'): self.reading_source = False self.reading_destination = True print('found dest') self.datadict[self.rule]['destinations'] = { } continue elements = item.split() if self.reading_source: self.datadict[self.rule]['sources'].append(elements[1]) else: self.datadict[self.rule]['destinations'].append(elements[1]) # Save last item self.save_item() json.dump(self.alldata, fo) def save_item(self): self.alldata.append(self.datadict) self.datadict = {} self.source = None self.rule = None self.dest = None self.reading_source = False self.reading_destination = False def readback_test(self): self.alldata = [ ] with self.dataout.open() as f: self.alldata = json.load(f) for item in self.alldata: print(item) if __name__ == '__main__': pd = ParseData() pd.readback_test()