import json import codecs newdata = {} with open('data.txt') as json_file: data = json.load(codecs.open('data.txt','r','utf-8-sig')) #print(data) i = 1 data_bc = data['BarCodeList'] for bc in data_bc: print(i) i = i + 1 barcode = bc['BARCODE'] try: hsn = bc['HSN'] except: hsn = 'not available' try: gst = bc['GST%'] except: gst = 'not available' try: item_name = bc['ITEM NAME'] except: item_name = 'not available' try: mrp = bc['MRP'] except: mrp = 'not available' newdata[barcode] = [] newdata[barcode] = ({ 'hsn': hsn, 'gst': gst, 'item_name': item_name, 'mrp': mrp }) with open('new_bc.txt','w') as outfile: json.dump(newdata, outfile)