Python Python에서 JSON으로 변환
파이썬에서 JSON으로 변환
json.dumps()
Python 객체가 있는 경우 메서드 를 사용하여 이를 JSON 문자열로 변환할 수 있습니다 .
예시
Python에서 JSON으로 변환:
import json
# a Python object (dict):
x = {
"name":
"John",
"age": 30,
"city": "New York"
}
#
convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
다음 유형의 Python 객체를 JSON 문자열로 변환할 수 있습니다.
- 딕셔너리
- 목록
- 튜플
- 끈
- 정수
- 뜨다
- 진실
- 거짓
- 없음
예시
Python 객체를 JSON 문자열로 변환하고 값을 인쇄합니다.
import json
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple",
"bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
Python에서 JSON으로 변환할 때 Python 객체는 해당하는 JSON(JavaScript)으로 변환됩니다.
Python | JSON |
---|---|
dict | Object |
list | Array |
tuple | Array |
str | String |
int | Number |
float | Number |
True | true |
False | false |
None | null |
예시
모든 유효한 데이터 유형을 포함하는 Python 객체를 변환합니다.
import json
x = {
"name":
"John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets":
None,
"cars": [
{"model": "BMW 230", "mpg":
27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))