Files

31 lines
928 B
Python

"""Tiny JSON file helpers shared by the web modules and the pipeline scripts."""
import json
import os
def read_json(path, default):
try:
with open(path, encoding="utf-8") as fh:
return json.load(fh)
except (OSError, ValueError):
return default
def write_json_atomic(path, data, **kw):
"""Write to PATH.tmp and rename over PATH (readers never see a half-written file)."""
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(data, fh, **kw)
os.replace(tmp, path)
def read_json_dict(path):
"""Like read_json(path, {}), but anything that is not a JSON object also gives {}."""
d = read_json(path, {})
return d if isinstance(d, dict) else {}
def write_json_compact(path, data):
"""write_json_atomic with the compact separators the classifier / archive indexes use."""
write_json_atomic(path, data, separators=(",", ":"))