Nous.Eval.CanonicalJSON (nous v0.21.1)

Copy Markdown View Source

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 \u00XX in 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), so 1 from YAML and 1.0 from a Python-written JSONL file hash the same
  • nil, true, false as null, 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 (:a and "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.

The content hash of term: "sha256:" followed by the lowercase hex SHA-256 of encode/1.

Functions

encode(term)

@spec encode(term()) :: String.t()

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"

hash(term)

@spec hash(term()) :: String.t()

The content hash of term: "sha256:" followed by the lowercase hex SHA-256 of encode/1.