1. json파일 읽기
import json with open('C:\\test.json', 'r') as f: json_data = json.load(f) |
- 읽은 json 파일 출력하기
| print(json.dumps(json_data) ) print(json.dumps(json_data, indent="\t") ) # align 맞추어 출력하기 |
2. json 파일 내의 특정 key의 내용만 출력하기
| result = json_data['key1']['key2'] # key1의 요소인 key2의 내용을 출력 print(result) |
3. json 파일 수정하기
| json_data['key1']['key2'] = "7000" # key1의 요소인 key2의 내용을 7000으로 변경 print(json_data['key1']['key2']) # 7000이 출력됨 |
4. python 코드로 json 파일 저장하기
예시
| import json car_group = dict() k5 = dict() k5["price"] = "5000" k5["year"] = "2015" car_group["K5"] = k5 avante = dict() avante["price"] = "3000" avante["year"] = "2014" car_group["Avante"] = avante #json 파일로 저장 with open('C:\\test.json', 'w', encoding='utf-8') as make_file: json.dump(car_group, make_file, indent="\t") # 저장한 파일 출력하기 with open('C:\\test.json', 'r') as f: json_data = json.load(f) print(json.dumps(json_data, indent="\t") ) |
- 결과
| { "K5": { "price": "5000", "year": "2015" }, "Avante": { "price": "3000", "year": "2014" } } |
'SW > Python' 카테고리의 다른 글
| [Python] 리스트 분할 split 나누기 자르기 (0) | 2023.12.18 |
|---|