Deterministic JSON encoding for content hashes.
Dataset hashes and run fingerprints are "sha256:" <> hex digests of this
encoding. The format is documented so other tools can recompute a hash
from the same data:
- object keys sorted by their UTF-8 bytes, at every depth
- no insignificant whitespace
- strings: UTF-8, only
",\and control characters below U+0020 are escaped (\b \f \n \r \t, otherwise\u00XXin lowercase hex); no Unicode normalization (the bytes are the content) - integers in decimal; a float with an integral value below 2^53 encodes
as that integer (
1.0->1), other floats in the shortest form that round-trips (0.1), so1from YAML and1.0from a Python-written JSONL file hash the same nil,true,falseasnull,true,false; any other atom as its string (:superset->"superset",MyApp.Scorer->"Elixir.MyApp.Scorer")- map keys may be strings or atoms (atoms become strings); two keys with
the same string form (
:aand"a") are an error
Structs, tuples, functions, pids and other terms have no JSON form and
raise ArgumentError: callers turn them into plain data first, so the
hash never depends on how a struct happens to be laid out.
Elixir's JSON.encode!/1 is not used because it does not sort the keys of
maps with more than 32 entries.
Summary
Functions
Encodes term as canonical JSON.
Raises ArgumentError for a term with no JSON form (see the moduledoc).
Examples
iex> Nous.Eval.CanonicalJSON.encode(%{"b" => [1, 2.5, nil], a: "x"})
~s({"a":"x","b":[1,2.5,null]})
iex> Nous.Eval.CanonicalJSON.encode(1.0)
"1"
The content hash of term: "sha256:" followed by the lowercase hex
SHA-256 of encode/1.