Canonical JSON Hash For Value Comparison
Hash JSON payloads deterministically by decoding into any and re-marshaling, so two payloads that differ only in map key order produce the same digest.
Code
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
)
// canonicalHash decodes raw JSON into any and re-marshals:
// json.Marshal writes the keys of a decoded map in sorted order,
// so payloads differing only in key order hash to the same digest
func canonicalHash(raw []byte) (string, error) {
var v any
if err := json.Unmarshal(raw, &v); err != nil {
return "", err
}
b, err := json.Marshal(v)
if err != nil {
return "", err
}
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:]), nil
}
func main() {
a := []byte(`{"host":"db1","port":5432,"tls":true}`)
b := []byte(`{"tls":true,"port":5432,"host":"db1"}`)
ha, err := canonicalHash(a)
if err != nil {
fmt.Println(err)
return
}
hb, _ := canonicalHash(b)
fmt.Println("a:", ha[:16])
fmt.Println("b:", hb[:16])
fmt.Println("value comparison:", ha == hb)
// genuinely different content: the digests must differ
c := []byte(`{"host":"db2","port":5432,"tls":true}`)
hc, _ := canonicalHash(c)
fmt.Println("a vs c equal:", ha == hc)
}How it works
All of the logic lives in the functions canonicalHash and main.
Every fallible call checks err != nil (3 sites), so an error is handled where it happens rather than bubbling invisibly.
Points of care
- There are no exceptions to catch —
errreturn values must be checked at each call site.
Putting it to use
The signature that matters: func canonicalHash(raw []byte) (string, error)
Running the file prints labeled results such as a:, b:, value comparison: — each operation’s effect is visible in the output.
The entry point wires canonicalHash together — run it once and the whole demo flows.
Core lines under the microscope
func canonicalHash(raw []byte) (string, error) {
var v any
if err := json.Unmarshal(raw, &v); err != nil {
return "", err
}
b, err := json.Marshal(v)
if err != nil {
return "", err
}
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:]), nil
}
if err != nil {
fmt.Println(err)
return
}
Interactive Tools for This Topic
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- How are errors reported?
- As returned `error` values, checked at 3 sites — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
- What does Canonical JSON Hash For Value Comparison print when run?
- No setup needed: run the file and look for labeled lines like `a:`, `b:`, `value comparison:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.