반응형
Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | |||||
| 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 10 | 11 | 12 | 13 | 14 | 15 | 16 |
| 17 | 18 | 19 | 20 | 21 | 22 | 23 |
| 24 | 25 | 26 | 27 | 28 | 29 | 30 |
| 31 |
Tags
- Tkinter
- Kotlin
- Excel
- 파이썬
- Apache
- Github
- array
- PANDAS
- dataframe
- Presto
- hive
- string
- c#
- gas
- GIT
- list
- SQL
- matplotlib
- PySpark
- numpy
- Redshift
- Java
- PostgreSQL
- math
- Google Excel
- google apps script
- Google Spreadsheet
- Python
- django
Archives
- Today
- Total
달나라 노트
Python json : dictionary를 JSON 파일로 생성하기 본문
728x90
반응형
dictionary를 JSON data로 바꾸고 .json 파일을 생성해봅시다.
- 참고 = dictionary <-> json 변환
https://cosmosproject.tistory.com/758
import json
dict_data = {
"category": "fruits",
"product_cnt": 2,
"product": {
"Apple": {
"price": 20000,
"weight": 3
},
"Watermelon": {
"price": 18000,
"screen_size": 2
},
}
}
json_data = json.dumps(dict_data)
print(json_data)
print(type(json_data))
with open('json_data.json', 'w') as f:
f.write(json_data)
dictionary를 json data로 변환한 후 with을 이용하면 간단하게 .json 파일을 생성할 수 있습니다.

위 코드를 실행하면 위 이미지처럼 json_data.json이 생성된 것을 볼 수 있죠.

.json 파일의 내용 또한 변환된 그대로 생성되었음을 알 수 있습니다.
import json
dict_data = {
"category": "fruits",
"product_cnt": 2,
"product": {
"Apple": {
"price": 20000,
"weight": 3
},
"Watermelon": {
"price": 18000,
"screen_size": 2
},
}
}
json_data = json.dumps(dict_data, indent=4)
print(json_data)
print(type(json_data))
with open('output/json_data.json', 'w') as f:
f.write(json_data)
- with open('output/json_data.json', 'w') as f:
만약 특정 경로에 .json 파일을 생성하고 싶으면 위처럼 상대 경로 / 절대 경로를 적어주면 됩니다.

경로에 적힌대로 output directory 안에 json_data.json 파일이 생성된 것을 볼 수 있습니다.
728x90
반응형
'Python > Python Basic' 카테고리의 다른 글
Comments
