Pythonのdata処理と実行環境5 / 9
Pythonとの変換とfile
import json
text = '{"name":"R1","enabled":true,"description":null}'
obj = json.loads(text)
assert obj["enabled"] is True
assert obj["description"] is None
encoded = json.dumps(obj, ensure_ascii=False, allow_nan=False)
with open("device.json", "w", encoding="utf-8") as handle:
json.dump(obj, handle, ensure_ascii=False, indent=2, allow_nan=False)
with open("device.json", encoding="utf-8") as handle:
restored = json.load(handle)
loads/dumpsはstringとの変換、load/dumpはfile等のstreamとの変換を扱う。withはblock終了時にfileを閉じる。Pythonの標準decoderは一部の非標準値も受け付けるため、標準JSONだけを扱う入力検証ではその条件も設定する。生成側はallow_nan=FalseでNaN等を拒否できる。