r
: 읽기 모드w
: 쓰기 모드a
: 추가open()
: 파일열기
read()
: 파일 전체 내용 읽기
readline()
: 파일 한 줄씩 읽기
json.load
: JSON파일을 Python 객체(딕셔너리)로 변환
import json
# JSON 문자열
json_data = '{"name": "John", "age": 30, "city": "New York"}'
# JSON 문자열을 Python 객체로 변환
data = json.loads(json_data)
# Python 객체 출력
print(data)
print(type(data))
json.dump
: 파이썬 객체를 json파일로 변환
import json
# Python 객체
data = {'name': 'John', 'age': 30, 'city': 'New York'}
# Python 객체를 JSON 파일로 변환
with open('dump.json', 'w') as file:
json.dump(data, file)
실행하게 되면 밑과 같이 작성된 dump.json이라는 파일이 생성됩니다.
{"name": "John", "age": 30, "city": "New York"}
pip install requests
를 하고 import
를 해주어야 합니다.
해당 주소는 테스트하기 위한 연습 코드들이 담긴 사이트입니다.
파일 실행 시 해당 페이지에 담긴 데이터들이 출력 됩니다.
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts')
print(response.text)
data = {'title': 'foo', 'body': 'bar', 'userId': 1}
response = requests.post(
'https://jsonplaceholder.typicode.com/posts', data=data)
print(response.text)
import requests
data = {'title': 'foo', 'body': 'bar', 'userId': 1}
response = requests.put(
'https://jsonplaceholder.typicode.com/posts/1', data=data)
print(response.text)
response = requests.delete('https://jsonplaceholder.typicode.com/posts/1')
print(response.text)
요청을 확인하는 방법으로 postman을 쓰고 있지만 더 빠른 개발을 추구할 때에는 curl가 좋은 선택지일 것 같습니다. 사용 예시는 아래와 같습니다.
curl -X POST -d "title=foo&body=bar&userId=1" https://jsonplaceholder.typicode.com/posts
curl -X PUT -d "title=foo&body=bar&userId=1" https://jsonplaceholder.typicode.com/posts/1
curl -X DELETE https://jsonplaceholder.typicode.com/posts/1