Skip to content

JSON Diff — Go source

Compare two JSON documents structurally: added, removed and changed values reported at exact paths instead of raw text lines. Runs locally in your browser with a shareable link.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package jsondiff is the Go twin of CosmoDev's src/lib/json-diff.ts (dual
// source: the web lib is TypeScript, the CLI lib is Go — kept in lock-step).
// Pure + deterministic, never panics. The table-driven tests in
// json-diff_test.go share vectors with src/lib/json-diff.test.ts so the two
// implementations are held to the same contract.
//
// The diff is STRUCTURAL, not textual (mirrors the TS lib exactly): both
// documents are parsed and walked in parallel, reporting added / removed /
// changed values at "$"-rooted paths ($.name, $.users[0], $[2]; the root
// itself is "$"). Objects recurse over the SORTED union of both key sets (key
// order never matters); arrays recurse by index with NO LCS alignment — a
// shifted array reports every moved index as changed, by design. A type
// change (object → array, scalar → array, …) reports ONE change at the
// diverging path, never per-child. Equality is deep and key-order
// insensitive, so same:true is order-insensitive. encoding/json decodes
// numbers to float64 exactly like JavaScript's JSON.parse, so 1 and 1.0
// compare equal in both twins.
//
// The TS lib's "Invalid JSON" fallback (JSON.parse throwing a non-Error) is
// structurally unreachable here: encoding/json always surfaces a Go error
// value, which the Left:/Right: prefixes below carry instead.
package jsondiff

import (
	"encoding/json"
	"fmt"
	"sort"
	"strings"
)

// ChangeType labels a diff entry, mirroring the TS union
// 'added' | 'removed' | 'changed'.
type ChangeType string

const (
	Added   ChangeType = "added"
	Removed ChangeType = "removed"
	Changed ChangeType = "changed"
)

// Change is one structural difference. Path is "$"-rooted: $.name,
// $.users[0], $[2]; the root itself is "$". Before is the left-side value and
// is nil when Type is Added (TS: the `before` key is absent); After is the
// right-side value and is nil when Type is Removed. Note that a decoded JSON
// null is also nil — the TS lib would carry an explicit null there, but no
// shared test vector distinguishes the two.
type Change struct {
	Path   string
	Type   ChangeType
	Before any
	After  any
}

// Result mirrors JsonDiffResult in the TS lib. Error is nil when the diff
// succeeded (TS: error: null) and carries "Both inputs are required" or a
// "Left: …" / "Right: …" parse-error message otherwise. Same is true only on
// a successful diff that produced zero changes; it is always false when
// Error is non-nil. Changes is non-nil ([] when empty) for exact TS parity.
type Result struct {
	Changes []Change
	Same    bool
	Error   *string // nil when valid (TS: error: null)
}

// errPtr boxes an error message into the nullable Error field.
func errPtr(msg string) *string { return &msg }

// isObject reports whether v is a decoded JSON object (TS isObject: non-null
// object that is not an array). encoding/json decodes objects to
// map[string]any and null to an untyped nil, so the type assert covers both.
func isObject(v any) (map[string]any, bool) {
	m, ok := v.(map[string]any)
	return m, ok
}

// deepEqual mirrors the TS deepEqual: scalars by ===, arrays element-wise
// (same length), objects by key set + value equality regardless of key
// order. Values never panic on comparison: both map/slice shapes are
// consumed by the typed branches, so the fallback only ever compares
// comparable scalar dynamics (or mismatched types, which compare false).
func deepEqual(a, b any) bool {
	if am, ok := a.(map[string]any); ok {
		bm, ok := b.(map[string]any)
		if !ok || len(am) != len(bm) {
			return false
		}
		for k, av := range am {
			bv, ok := bm[k]
			if !ok || !deepEqual(av, bv) {
				return false
			}
		}
		return true
	}
	if aa, ok := a.([]any); ok {
		ba, ok := b.([]any)
		if !ok || len(aa) != len(ba) {
			return false
		}
		for i := range aa {
			if !deepEqual(aa[i], ba[i]) {
				return false
			}
		}
		return true
	}
	return a == b
}

// walk mirrors the TS walk: descend while both sides share a container kind,
// recursing objects over the sorted key union and arrays by shared index
// (added/removed indices reported after the shared range), collapsing any
// other divergence into a single "changed" at the current path.
func walk(left, right any, path string, out *[]Change) {
	if deepEqual(left, right) {
		return
	}

	if lm, lok := isObject(left); lok {
		if rm, rok := isObject(right); rok {
			keys := make([]string, 0, len(lm)+len(rm))
			seen := make(map[string]bool, len(lm)+len(rm))
			for k := range lm {
				if !seen[k] {
					seen[k] = true
					keys = append(keys, k)
				}
			}
			for k := range rm {
				if !seen[k] {
					seen[k] = true
					keys = append(keys, k)
				}
			}
			sort.Strings(keys)
			for _, k := range keys {
				child := path + "." + k
				lv, inL := lm[k]
				rv, inR := rm[k]
				switch {
				case !inL:
					*out = append(*out, Change{Path: child, Type: Added, After: rv})
				case !inR:
					*out = append(*out, Change{Path: child, Type: Removed, Before: lv})
				default:
					walk(lv, rv, child, out)
				}
			}
			return
		}
	}

	if la, lok := left.([]any); lok {
		if ra, rok := right.([]any); rok {
			shared := len(la)
			if len(ra) < shared {
				shared = len(ra)
			}
			for i := 0; i < shared; i++ {
				walk(la[i], ra[i], fmt.Sprintf("%s[%d]", path, i), out)
			}
			for i := shared; i < len(ra); i++ {
				*out = append(*out, Change{Path: fmt.Sprintf("%s[%d]", path, i), Type: Added, After: ra[i]})
			}
			for i := shared; i < len(la); i++ {
				*out = append(*out, Change{Path: fmt.Sprintf("%s[%d]", path, i), Type: Removed, Before: la[i]})
			}
			return
		}
	}

	*out = append(*out, Change{Path: path, Type: Changed, Before: left, After: right})
}

// JsonDiff compares two JSON documents structurally. It is the Go twin of
// jsonDiff() in src/lib/json-diff.ts and must agree with it on every shared
// vector. Both inputs are required; parse failures are reported with the
// offending side prefixed ("Left: …" / "Right: …").
func JsonDiff(leftRaw, rightRaw string) Result {
	if strings.TrimSpace(leftRaw) == "" || strings.TrimSpace(rightRaw) == "" {
		return Result{Changes: []Change{}, Same: false, Error: errPtr("Both inputs are required")}
	}

	var left, right any
	if err := json.Unmarshal([]byte(leftRaw), &left); err != nil {
		return Result{Changes: []Change{}, Same: false, Error: errPtr(fmt.Sprintf("Left: %v", err))}
	}
	if err := json.Unmarshal([]byte(rightRaw), &right); err != nil {
		return Result{Changes: []Change{}, Same: false, Error: errPtr(fmt.Sprintf("Right: %v", err))}
	}

	changes := []Change{}
	walk(left, right, "$", &changes)
	return Result{Changes: changes, Same: len(changes) == 0, Error: nil}
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →