위와 같은 234개의 데이터를 {id: 1, name: "강남구", cityId: 1}
이런 형식으로 바꿔줘야 했다. 이 데이터가 왜 필요하느냐.. 광역시도
와 시군구
를 선택할 수 있는 dropdown
을 구현하고 있기 때문이다.
하나하나 다 작성하기엔 무리라서 쉽게 바꿀 수 있는 방법을 찾아봤다.
excel 파일을 csv
파일로 바꾸고, python
코드로 json
으로 변환해주면 된다!
참고로 아래의 코드는 바꿀 대상인 area_code_data (2).csv
파일과 hangjungdong.py
가 같은 경로에 위치했다.
import csv
import json
# csv 파일 경로
csv_file_path = 'area_code_data (2).csv'
# csv 파일 읽어오기
with open(csv_file_path, 'r', encoding='cp949') as f:
reader = csv.reader(f)
next(reader) # 첫 줄 skip
# 각 라인마다 딕셔너리 생성 후 리스트에 추가
data = []
for line in reader:
d = {
'id': int(line[0]),
'name': line[1],
'cityId': int(line[2])
}
data.append(d)
# json string으로 변환
json_string = json.dumps(data, ensure_ascii=False, indent=2)
# print(json_string)
# txt 파일로 저장할 경로
txt_file_path = 'data.txt'
# txt 파일 쓰기
with open(txt_file_path, 'w', encoding='utf-8') as f:
f.write(json_string)
위의 코드를 통해 아래와 같은 txt 파일을 얻을 수 있었다.
하나하나 작성할 뻔했는데 덕분에 빠르게 작업할 수 있었고, 똑똑해진 기분,,