Skip to content

Instantly share code, notes, and snippets.

@nockn
Last active October 21, 2021 06:21
Show Gist options
  • Save nockn/5be5a90e7b6156fd289105373bfbdb09 to your computer and use it in GitHub Desktop.
Save nockn/5be5a90e7b6156fd289105373bfbdb09 to your computer and use it in GitHub Desktop.
[note] How to load jsonc file
import json
import os
import re
from chardet.universaldetector import UniversalDetector
def get_text_encoding(file):
"""
ファイルの中身の文字コードを調べる
Args:
file: ファイルの中身
Returns:
detector.result["encoding"](str): 文字コード
"""
detector = UniversalDetector()
for binary in file:
detector.feed(binary)
if detector.done:
break
detector.close()
return detector.result["encoding"]
def read_jsonc(filepath: str, encode: str):
"""read_jsonc
jsoncファイルをjsonとして読み込む
Args:
filepath: (str)jsoncファイルのパス
encode: (str)jsoncファイルの文字コード
Returns:
json_obj: (dict)json
Notes:
設定を書き込むjsonはコメントに対応していない。
そこでコメントが書けるjsoncを、なんやかんやしてPython内部ではjsonとして扱う。
"""
with open(filepath, "r", encoding=encode) as f:
text = f.read() # jsoncの中身を取得
re_text = re.sub(r"/\*[\s\S]*?\*/|//.*", "", text) # コメントを削除
json_obj = json.loads(re_text) # JSONとして解釈
return json_obj # 辞書型を返す
if __name__ == '__main__':
config_path = os.path.join(os.path.dirname(__file__), "config.jsonc")
config_data = read_jsonc(config_path, get_text_encoding(config_path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment