본문 바로가기
DEV/Web 개발

Web 개발 :: 프로젝트 CSV, JSON 데이터 다루기_TIL65

by 올커 2022. 12. 7.

■ JITHub 개발일지 65일차

□  TIL(Today I Learned) ::

프로젝트 CSV, JSON 데이터 다루기_TIL65

 - 크롤링한 데이터를 DB(sqlite3)와 csv, json 사이에서 자유자재로 복사, 이동, 업로드해야 할 필요가 있었다.

 - 보통 준비되는 json 파일은 아래와 같이 model의 table 정보가 없다.

[
    {
    "score_taste": "5",
      "score_service": "1",
      "score_cleanliness": "3"
    }
    {
    "score_taste": "2",
      "score_service": "3",
      "score_cleanliness": "2"
    }
    ...
]

 - 아래 코드는 json파일을 DB 테이블에 업로드하기 위해 수정해주는 코드이다.

   {"model":"places.place"} 부분이 table을 지정해주는 코드이다.

import random
import json


new_list = []
for i in range(301):
    new_data = {"model":"places.place"}
    new_dict = {}
    new_dict['score_taste'] = random.randint(1, 5)
    new_dict['score_service'] = random.randint(1, 5)
    new_dict['score_cleanliness'] = random.randint(1, 5)
    new_data["fields"] = new_dict
    new_list.append(new_data)

with open('place_score.json', 'w', encoding='UTF-8') as f:
    json.dump(new_list, f, ensure_ascii=False, indent=2)

 

 - 아래 코드는 기존에 있던 장소에 위에서 작성한 필드 (score_taste, score_service, score_cleanliness)를 추가하여 수정한 후 다시 최종적으로 db에 적용하는 코드이다.

import json

with open('data.json', 'r',encoding='utf-8-sig') as f:
    place_data = json.load(f)

new_list = []
for data in place_data:
    new_data = {'model': 'places.place'}
    new_data["fields"] = data
    new_list.append(new_data)
    
with open('place_data_fin.json', 'w', encoding='UTF-8') as f:
    json.dump(new_list, f, ensure_ascii=False, indent=2)

 - json파일이 model, fields 구분하에 잘 생성된 것을 확인할 수 있었다.

[
  {
    "model": "places.place",
    "fields": {
      "place_name": "꼭그닭 강남점",
      "category": "치킨,닭강정",
      "place_number": "0507-1401-5335",
      "rating": "4.45",
      "place_address": "서울 강남구 봉은사로4길 37 지하 1층",
      "place_time": "23:00에 라스트오더",
      "place_img": "https://search.pstatic.net/common/?autoRotate=true&type=w560_sharpen&src=https%3A%2F%2Fldb-phinf.pstatic.net%2F20211220_35%2F1639982589696IpAyt_JPEG%2F1639906280173-0.jpg",
      "score_taste": "5",
      "score_service": "1",
      "score_cleanliness": "3"
    }
  },
  {
    "model": "places.place",
    "fields": {
      "place_name": "한추",
      "category": "맥주,호프",
      "place_number": "02-541-0969",
      "rating": "4.19",
      "place_address": "서울 강남구 논현로175길 68",
      "place_time": "새벽 00:30에 라스트오더",
      "place_img": "https://search.pstatic.net/common/?autoRotate=true&type=w560_sharpen&src=https%3A%2F%2Fldb-phinf.pstatic.net%2F20200418_224%2F1587220460095GXDPA_JPEG%2FoCJwGKvw4sZpUhYtL6-dfF4R.jpeg.jpg",
      "score_taste": "2",
      "score_service": "3",
      "score_cleanliness": "2"
    }
  },

 

 

반응형

댓글