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.

GoData Integrity

Code

gosnippet
44 lines
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 — err return 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

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.