Skip to main content

Getting Started

Install​

dotnet add package UnambitiousFx.Engram

Engram targets net8.0, net9.0, net10.0 and net11.0 and has no dependency beyond the BCL.

Canonicalize​

Everything is on one static class, JsonCanonicalizer, in the UnambitiousFx.Engram namespace.

using UnambitiousFx.Engram;

var json = """{ "b": [1, 2.50], "a": "x" }""";

string canonical = JsonCanonicalizer.Canonicalize(json);
// {"a":"x","b":[1,2.5]}

Fingerprint​

string hash = JsonCanonicalizer.Hash(json);
// 64 lowercase hexadecimal characters: the SHA-256 of the UTF-8 canonical form

Two texts with the same data have the same fingerprint, whatever their formatting.

Inputs​

Canonicalize, CanonicalizeToUtf8 and Hash all accept the same inputs:

InputExample
JSON textJsonCanonicalizer.Hash("""{"a":1}""")
UTF-8 bytesJsonCanonicalizer.Hash(body.AsSpan())
JsonElementJsonCanonicalizer.Hash(document.RootElement)
JsonNode?JsonCanonicalizer.Hash(node); a null node is JSON null
A typed valueJsonCanonicalizer.Hash(order, AppJsonContext.Default.Order)

The typed overload serializes through the source-generated JsonTypeInfo<T> of a JsonSerializerContext, so it works under trimming and NativeAOT:

public record Order(string Currency, decimal Amount);

[JsonSerializable(typeof(Order))]
public partial class AppJsonContext : JsonSerializerContext;

var fingerprint = JsonCanonicalizer.Hash(new Order("EUR", 12.50m), AppJsonContext.Default.Order);
note

A string argument is parsed as JSON text. To canonicalize a JSON string value, pass a JsonNode: JsonCanonicalizer.Canonicalize(JsonValue.Create("text")) gives "text".

Errors​

ExceptionWhen
JsonExceptionThe text is not valid JSON.
FormatExceptionThe value has no RFC 8785 canonical form: a duplicate member name, a number outside the double range, a lone surrogate.

Catch them where the JSON enters your system, as you would for any parsing.