Stable content hash for a record

easyPipelines~15 min · 9 tests

Two copies of the same event should get the same ID, even if one has its keys in a different order or a different ingested_at. A content hash gives you that ID. It only works if the bytes you hash are the same every time.

Write record_hash(record, ignore=()):

  • record is a dict of JSON-friendly values: strings, numbers, bools, None, lists and nested dicts.
  • Drop any top-level key named in ignore.
  • Turn what’s left into canonical JSON: keys sorted at every level, no spaces ("," and ":" as separators), and non-ASCII characters written as-is rather than as \u escapes.
  • Encode that string as UTF-8 and return the SHA-256 hex digest (64 lowercase hex characters).
  • Don’t change the input dict.
>>> record_hash({"b": 1, "a": 2}) == record_hash({"a": 2, "b": 1})
True
>>> record_hash({"a": 1})
'015abd7f5cc57a2dd94b7590f04ad8084273905ee33ec5cebeae62276a97f862'
Learn the ideaRead the lesson →
solution.pyPython 3.14 · Pyodide

Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.

⌘ ↵ to run