가끔 아래처럼 하나의 파일에서 여러 불특정 json이 섞여 있는 경우에 특정 value만 뽑을 때 사용하는 방법
{"fruit": "Apple", "size": "Large", "color": "Red"}
{"name": "User_name1", "Hobby": "Baseball"}
{"fruit": "Orange", "size": "Medium", "color": "Yellow"}
{"menu": "Coffee", "Type": "iced"}
{"fruit": "Strawberry", "size": "Small", "color": "Red"}
color가 Red인 fruit을 뽑고 싶은데 json 파싱 후 data['color'] 만 사용할 경우 혹은 data.get('color')만 사용할 경우 color에 대한 key가 없는 row에서 에러가 발생하게 된다.
물론 exception처리를 하거나 다른 방법이 있겠지만 간단하게 처리하는 방법을 기술한다.
아래처럼 json 파싱 후 data.get('color','None') 을 사용하여 key가 없을 경우에 None을 반환하도록 한다.
color_value = data.get('color', 'None')
전체적인 샘플 코드는 아래와 같다.
import json
json_data = [
{"fruit": "Apple", "size": "Large", "color": "Red"},
{"name": "User_name1", "Hobby": "Baseball"},
{"fruit": "Orange", "size": "Medium", "color": "Yellow"},
{"menu": "Coffee", "Type": "iced"},
{"fruit": "Strawberry", "size": "Small", "color": "Red"}
]
for line in json_data:
json_line = json.dumps(line)
data = json.loads(json_line)
color_value = data.get('color', 'None')
if "Red" in color_value:
print (f"{data['fruit']}\'s color is Red.")
결과
'IT > Python' 카테고리의 다른 글
Slack으로 알람 받기(Incoming Webhooks) (0) | 2023.05.01 |
---|---|
Python - 파일명에 속한 날짜를 기준으로 정렬 (2) | 2022.10.03 |
Python - 날짜를 기간설정하여 for문 (0) | 2022.10.01 |