[python] json

📝 1yangsh·2021년 10월 6일
0

파이썬을 기반으로 개발 시, 많이 사용하는 내장모듈 중 하나인 json에 대해 알아보자
아래 많이 사용하는 대표적 네 가지의 함수가 있다.

json.loads()

JSON 문자열python 객체로 변환

  • str -> dict

json.dumps()

python 객체JSON 문자열로 변환

  • dict -> json

json.load()

JSON 파일python 객체로 불러옴

  • data.json(json 파일) -> dict

json.dump()

python 객체JSON 파일에 저장

  • dict -> data.json(json 파일)

참고

디폴트로 변환되는 JSON 문자열은 위와 같이 한 줄이기 때문에 Python 객체가 많은 데이터를 담고 있는 경우, 가독성이 떨어질 수 있습니다. 이럴 경우, indent 파라미터에 숫자를 넘기면 그 만큼 들여쓰기가 되어 JSON 문자열로 변환이 됩니다.

ex)

mport json

json_object = {"id": 1,
    "username": "John",
    "email": "John@google.com",}

json_string = json.dumps(json_object, indent=2)
print(json_string)

indent 없는 output

{"id": 1,"username": "John","email": "John@google.com"}

indent=2 output

{
  "id": 1,
  "username": "John",
  "email": "John@google.com"
}

참고

profile
개발 경험 저장소

0개의 댓글