Python 에서 JSON 파일을 예쁘게 인쇄하는 방법
JSON 파일을 문자열로 읽거나 ‘로드’하면 내용이 지저분해질 수 있습니다.
예를 들어 하나의 JSON 파일에서
[{"foo": "Etiam", "bar": ["rhoncus", 0, "1.0"]}]
당신이로드하고인쇄한다면.
import json
with open(r"C:\test\test.json", "r") as f:
json_data = json.load(f)
print(json_data)
[{"foo": "Etiam", "bar": ["rhoncus", 0, "1.0"]}]
결과는 일반적으로 볼 수있는 * standard * 형식과 비교하여 잘 읽을 수 있습니다.
[
{
"foo": "Etiam",
"bar": [
"rhoncus",
0,
"1.0"
]
}
]
json.dumps 메소드
json.dumps()함수는 주어진 obj 를 JSON 형식 str 로 직렬화합니다.
json.dumps()함수에서 키워드 매개 변수 indent 에 양의 정수를 주어 주어진 들여 쓰기 레벨로 obj 를 예쁘게 인쇄해야합니다. ident 가 0으로 설정되면, 새로운 줄만 삽입합니다.
import json
with open(r"C:\test\test.json", "r") as f:
json_data = json.load(f)
print(json.dumps(json_data, indent=2))
[{"foo": "Etiam", "bar": ["rhoncus", 0, "1.0"]}]
pprint 방법
pprint 모듈은 파이썬 데이터 구조를 예쁘게 인쇄하는 기능을 제공합니다. pprint.pprint 는 파이썬 객체를 스트림에 출력하고 그 뒤에 개행을 출력합니다.
import json
import pprint
with open(r"C:\test\test.json", "r") as f:
json_data = f.read()
json_data = json.loads(json_data)
pprint.pprint(json_data)
JSON 파일 데이터 내용이 예쁘게 인쇄됩니다. 그리고 들여 쓰기 매개 변수를 할당하여 들여 쓰기를 정의 할 수도 있습니다.
pprint.pprint(json_data, indent=2)
pprint 는 작은 '와 큰 따옴표 "를 동일하게 취급하지만 JSON 은"만 사용하므로 pprinted JSON 파일 내용을 파일에 직접 저장할 수 없습니다.
그렇지 않으면 새 파일이 유효한 JSON 형식으로 구문 분석되지 않습니다.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook