[Module] json 데이터에서 특정 키와 값을 삭제하는 모듈
Module
코드: https://github.com/lifeisgouda/my_python_modules/tree/master/json_key_remover
JSON 데이터에서 특정 key ( 여기서는 coordinates
) 에서 값이 [0, 0]
일 경우 해당 키를 삭제하는 모듈이다.
json의 뎁스가 워낙 깊고, 검사해야할 부분이 많아서 부득이하게 3중 for문이 사용되었다.
1class JSON_KEY_REMOVER:
2 def __init__(self):
3 self.data = []
4
5 def import_json(self, filename):
6 import json
7
8 with open(filename) as json_file:
9 self.data = json.load(json_file)
10
11 print('import json done')
12
13 def del_daily_zero_coordinates(self):
14 import json
15
16 for k in range(len(self.data)):
17 for i in range(len(self.data[k]["history"]["dateInformation"][2]["daily"])):
18 for j in range(0, 24):
19 if [0, 0] == self.data[k]["history"]["dateInformation"][2]["daily"][i]["dailyTimeline"]['dateT'+str(j)]["coordinates"]:
20 del self.data[k]["history"]["dateInformation"][2]["daily"][i]["dailyTimeline"]['dateT'+str(j)]["coordinates"]
21
22 with open('data.json', 'w', encoding='UTF-8-sig') as data_file:
23 self.data = json.dump(self.data, data_file, ensure_ascii=False)
24
25 print("Done!")
사용
1# main.py
2
3import json_key_remover
4
5remove = json_key_remover.JSON_KEY_REMOVER
6remove.import_json("./user.json")
7remove.del_daily_zero_coordinates()