Python - json.loads()

YJ·2023년 4월 9일
  • JSON 형식의 문자열을 입력으로 받아 해당 문자열을 파싱하여 Python의 list, dictionary 등으로 변환

  • josn.loads() 예제

  • json 형식 문자열

{
    "name": "yoojoon",
    "age": 25,
    "is_student": true,
    "subjects": ["computer", "math", "python"]
}
  • json 형식 문자열을 dictionary로 변환
import json

json_str = '{"name": "yoojoon", "age": 25, "is_student": true, "subjects": ["computer", "math", "python"]}'
data_dict = json.loads(json_str)

print(type(data_dict))  # 출력: <class 'dict'>
print(data_dict['name'])  # 출력: yoojoon
print(data_dict['age'])  # 출력: 25
print(data_dict['is_student'])  # 출력: True
print(data_dict['subjects'])  # 출력: ['computer', 'math', 'python']
  • 어디서 사용?
    • Socket을 사용한 Raw Connnection 시
      • json 형식의 문자열을 서버로부터 받을 경우
          1. 디코딩하여 bytes -> str
          1. HTTP 헤더와 json 데이터를 split으로 분리
          • HTTP 헤더와 json 데이터는 CRLF로 구분되어있음
            • '\r\n\r\n'으로 구분
          • split('\r\n\r\n')으로 분리 헤더와 데이터 분리
          1. json 데이터는 json 형식의 str임
          1. json.loads(json_data)로 str -> dictionary
          1. dictionary이므로 key값으로 원하는 필드의 값을 사용 가능
profile
dev

0개의 댓글