Python
[Python] json 파일에 주석 달기
bryan.oh
2021. 2. 11. 12:55
반응형
json file 에 주석달기
config.json 이라는 파일의 내용이 아래와 같다고 합시다.
{
"name": "bryan", /* 여기에 설명 쓰고싶을 때 */
"title": "helllo",
"url": "https://hello-bryan.tistory.com/",
"bookmark": true
/* 여기에도 주석 달고 싶을 때 */
}
이 파일을 json 로드한다면 오류가 나겠죠.
with open('config.json') as f:
json_data = json.load(f) # error
아래와 같이 사용하시면 됩니다.
with open('config.json', 'r', encoding='utf-8') as f:
contents = f.read()
while "/*" in contents:
preComment, postComment = contents.split('/*', 1)
contents = preComment + postComment.split('*/', 1)[1]
json_data = json.loads(contents.replace("'", '"'))
메소드를 하나 만들어서 쓰세요~
def getJsonData(config_path: str):
with open(config_path, 'r', encoding='utf-8') as f:
contents = f.read()
while "/*" in contents:
preComment, postComment = contents.split('/*', 1)
contents = preComment + postComment.split('*/', 1)[1]
return json.loads(contents.replace("'", '"'))
# exception 처리는 self
이제 json 파일에 설명 마구마구 넣읍시다.
728x90
반응형