### Install jd via go install Source: https://github.com/josephburnett/jd/blob/master/README.md Install the `jd` commandline utility using `go install`. ```bash go install github.com/josephburnett/jd/v2/jd@latest ``` -------------------------------- ### Install jd via mise Source: https://github.com/josephburnett/jd/blob/master/README.md Install the `jd` commandline utility using `mise`. ```bash mise use -g jd@latest ``` -------------------------------- ### Path Element Examples: List and Object Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Examples of list and object path elements. ```json 0 ``` ```json "foo" ``` -------------------------------- ### Install jd via Homebrew Source: https://github.com/josephburnett/jd/blob/master/README.md Install the `jd` commandline utility using the Homebrew package manager. ```bash brew install jd ``` -------------------------------- ### Path Element Examples: Set and Set Key Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Examples of set and set key path elements. ```json {} ``` ```json {"id":"foo"} ``` -------------------------------- ### Metadata Element Examples: List and Object Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Examples of list and object metadata elements. ```json [] ``` ```json (a string) ``` -------------------------------- ### Metadata Element Examples: Set and Multiset Keys Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Examples of set and multiset keys as metadata elements. ```json ["foo"] ``` ```json [["foo"]] ``` -------------------------------- ### Metadata Element Examples: Set and Multiset Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Examples of set and multiset metadata elements. ```json {} ``` ```json [{}] ``` -------------------------------- ### Path Element Examples: Multiset and Multiset Key Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Examples of multiset and multiset key path elements. ```json [{}] ``` ```json [{"id":"foo"}] ``` -------------------------------- ### PathOptions Example Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Applies specific options like 'SET' to a particular document path using PathOptions syntax. ```JSON ^ {"@": ["users"], "^": ["SET"]} ``` -------------------------------- ### View Changes in a Kubernetes Deployment Source: https://github.com/josephburnett/jd/blob/master/README.md This example shows how to view all changes in a Kubernetes deployment by diffing the current state against a saved YAML file. ```bash kubectl get deployment example -oyaml > a.yaml kubectl edit deployment example # change cpu resource from 100m to 200m kubectl get deployment example -oyaml | jd -yaml a.yaml ``` -------------------------------- ### DIFF_ON Option Example Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Demonstrates using 'DIFF_ON' to enable diffing at a specific path, overriding parent 'DIFF_OFF' settings. ```JSON ^ {"@": [], "^": ["DIFF_OFF"]} ``` ```JSON ^ {"@": ["data"], "^": ["DIFF_ON"]} ``` -------------------------------- ### Path Element Examples: Set Key with Non-String Key Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Example of a set key with a non-string key in a path element. ```json [true,"foo"] ``` -------------------------------- ### Install jd via Docker Source: https://github.com/josephburnett/jd/blob/master/README.md Run `jd` within a Docker container, mounting the current directory for file access. ```bash jd(){ docker run --rm -i -v $PWD:$PWD -w $PWD josephburnett/jd "$@"; } ``` -------------------------------- ### Path Element Examples: Multiset with Non-String Key Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Example of a multiset with a non-string key in a path element. ```json [[true,"foo"]] ``` -------------------------------- ### Metadata Element Examples: Object with Non-String Key Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Example of an object with a non-string key as a metadata element. ```json [(a value)] ``` -------------------------------- ### Path Element Examples: Object with Non-String Key Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Example of an object with a non-string key in a path element. ```json [true] ``` -------------------------------- ### Path Resolution Examples Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Illustrates how path elements navigate the document tree, mapping array indices and object keys to document properties. ```JSON ["users", 0, "name"] → document.users[0].name ``` ```JSON ["config", "timeout"] → document.config.timeout ``` ```JSON [] → document (root) ``` -------------------------------- ### Patch Application Error Example Source: https://github.com/josephburnett/jd/blob/master/spec/errors.md Illustrates a context mismatch error during patch application, showing the expected and found context values. ```text PATCH_CONTEXT_MISMATCH: Context validation failed Location: path ["items", 2] Expected: context value "apple" Found: "banana" Context: ["orange", "banana", "cherry"] ``` -------------------------------- ### Basic Structural Diff Example Source: https://github.com/josephburnett/jd/blob/master/spec/jd-format.md Demonstrates a simple change to an object property. Use this format for straightforward value modifications. ```diff @ ["user","name"] - "Alice" + "Bob" ``` -------------------------------- ### Metadata Line Examples Source: https://github.com/josephburnett/jd/blob/master/spec/jd-format.md Provides examples of metadata lines used in structural diffs to control comparison behavior. These lines are prefixed with '^' and contain JSON values. ```diff ^ "SET" ``` ```diff ^ {"precision":0.01} ``` ```diff ^ {"@":["path"],"^":["SET"]} ``` -------------------------------- ### Nested List Context Example 3 Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Shows how additional context is added if a patch does not have enough context to prevent double application. ```json [1,2,2,3] ``` ```json [1,2,2,2,3] ``` ```diff @ [2] 1 + 2 2 2 3 ``` -------------------------------- ### Example of Structural Sharing Source: https://github.com/josephburnett/jd/blob/master/doc/immutability.md Illustrates how structural sharing works by showing that only the modified path from the root to the changed node is copied, while subtrees remain shared. ```text Original: {a: 1, b: {c: 2, d: 3}, e: 4} Patch: set a = 10 Result: {a: 10, b: {c: 2, d: 3}, e: 4} ↑new ↑shared subtree ↑shared Only root object is new, all subtrees shared. ``` -------------------------------- ### Nested List Context Example 2 Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Illustrates context for producing minimal diffs when an element is at the beginning of a list. The patch applies only once. ```json [2,3] ``` ```json [1,2,3] ``` ```diff @ [0] + 1 2 ``` -------------------------------- ### SET Option Example Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Specifies the 'SET' option, which treats arrays as mathematical sets, ignoring order and duplicates for comparison. ```JSON ^ "SET" ``` -------------------------------- ### Apply SET semantics to 'users' path Source: https://github.com/josephburnett/jd/blob/master/spec/jd-format.md This example demonstrates how to apply SET semantics specifically to the 'users' path within a document. It uses PathOptions to target a specific path and override default diffing behavior. ```diff ^ {"@":["users"],"^":["SET"]} ``` -------------------------------- ### Example Option Conflict Source: https://github.com/josephburnett/jd/blob/master/spec/errors.md Highlights an option processing error where incompatible options are provided, such as using 'precision' with the 'SET' operation. ```text Options: ["SET", {"precision": 0.01}] Error: OPTION_CONFLICT: Precision option incompatible with SET (uses hash comparison) ``` -------------------------------- ### Example Parsing Error Message Source: https://github.com/josephburnett/jd/blob/master/spec/errors.md Provides an example of a parsing error message, detailing the specific syntax issue, location, and expected versus found elements. ```text DIFF_SYNTAX_ERROR: Invalid path array syntax Location: line 3, column 15 Expected: ']' to close path array Found: end of line Context: @ ["users", 0, "name" ``` -------------------------------- ### MULTISET Option Example Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Specifies the 'MULTISET' option, which treats arrays as multisets, ignoring order but counting duplicates. ```JSON ^ "MULTISET" ``` -------------------------------- ### Turn off diffing at root Source: https://github.com/josephburnett/jd/blob/master/doc/diff-on-off.md Example of turning off diffing for the entire document by specifying an empty path. ```json [{"@":[],"^":["DIFF_OFF"]}] ``` -------------------------------- ### Turn on diffing explicitly Source: https://github.com/josephburnett/jd/blob/master/doc/diff-on-off.md Example of explicitly turning on diffing for the `data` field. This is redundant if diffing is on by default but demonstrates valid usage. ```json [{"@":["data"],"^":["DIFF_ON"]}] ``` -------------------------------- ### Precision Option Example Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Sets a numeric comparison tolerance using the 'precision' option, considering numbers within this tolerance as equal. ```JSON ^ {"precision": 0.001} ``` -------------------------------- ### Configure Test Runner for Different Binaries Source: https://github.com/josephburnett/jd/blob/master/spec/test/README.md Adapt the runner to binaries with different flag names or exit codes using CLI mapping flags. This example shows custom options, patch flags, and error exit codes. ```bash ./test-runner -opts-flag=--options -patch-flag=--patch -error-exit=1 /path/to/your/binary ``` -------------------------------- ### Control diffing with DIFF_OFF and DIFF_ON Source: https://github.com/josephburnett/jd/blob/master/spec/jd-format.md This example shows how to selectively disable and enable diffing for specific document paths. DIFF_OFF ignores changes at specified paths, while DIFF_ON enables diffing, overriding parent DIFF_OFF settings. ```diff ^ {"@":["metadata"],"^":["DIFF_OFF"]} ^ {"@":["data"],"^":["DIFF_ON"]} ``` -------------------------------- ### Quick Benchmark Verification Source: https://github.com/josephburnett/jd/blob/master/doc/performance.md Makefile target for a quick verification run of benchmarks. It executes a specific benchmark for a limited duration to ensure the test setup is functional. ```makefile # Quick verification that benchmarks run benchmark-quick: cd v2 && go test -bench=BenchmarkPatch_Object_SingleValue -benchtime=100ms ``` -------------------------------- ### Standard Error Message Structure Example Source: https://github.com/josephburnett/jd/blob/master/spec/errors.md Illustrates the standard format for error messages, including code, location, expected and found values, and context. ```text ERROR_CODE: Brief description Location: file:line:column or path information Expected: what was expected (if applicable) Found: what was actually encountered Context: surrounding context (first 50 chars) ``` -------------------------------- ### Keys Option Example Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Defines specific keys for object matching within arrays using the 'keys' option, enabling object-level diffing. ```JSON ^ {"keys": ["id", "name"]} ``` -------------------------------- ### List Diffing Example Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Demonstrates list diffing using the Longest Common Subsequence (LCS) algorithm. This method preserves context and array order semantics. ```plaintext A: [1, 2, 3, 4] B: [1, 5, 6, 4] LCS: [1, 4] (common elements) Operations: remove 2,3 at index 1, add 5,6 at index 1 ``` -------------------------------- ### Array Context Preservation Example Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Demonstrates how minimal surrounding context is shown for array modifications in diffs, using specific formatting for additions and removals. ```Diff Original: ["a", "b", "c", "d"] Modified: ["a", "x", "y", "d"] Diff: @ [1] "a" ← context before (minimal) - "b" ← removal - "c" ← removal + "x" ← addition + "y" ← addition "d" ← context after (minimal) ``` -------------------------------- ### Set Diffing Example Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Illustrates set diffing where duplicates are removed and order is ignored. This method efficiently finds additions and removals using hash comparison. ```plaintext ^ "SET" A: [3, 1, 2, 1] → Set{1, 2, 3} B: [2, 4, 1] → Set{1, 2, 4} Removals: {3} Additions: {4} ``` -------------------------------- ### Nested List Context Example 1 Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Demonstrates context for inserting an element into the middle of a list to produce minimal diffs. The patch applies only once due to context. ```json [[1,2,3],[4,6],[7,8,9]] ``` ```json [[1,2,3],[4,5,6],[7,8,9]] ``` ```diff @ [1,1] 4 + 5 6 ``` -------------------------------- ### Multiple Hunks with Inheritance in JD Diff Source: https://github.com/josephburnett/jd/blob/master/README.md Demonstrates multiple diff hunks where options like merge semantics are inherited. The example shows changes to user preferences and last login time. ```diff ^ {"Merge":true} @ ["user","preferences"] + {"theme":"dark","notifications":true} @ ["user","lastLogin"] + "2023-12-01T10:30:00Z" ``` -------------------------------- ### Example Diff Format Syntax Error Source: https://github.com/josephburnett/jd/blob/master/spec/errors.md Illustrates a syntax error during diff format parsing where a path line is missing the '@' symbol. ```text Input: @ ["path" Output: DIFF_SYNTAX_ERROR: Unterminated path array at line 1, column 10 ``` -------------------------------- ### Example Path Resolution Error Message Source: https://github.com/josephburnett/jd/blob/master/spec/errors.md Demonstrates a path resolution error message, indicating a type mismatch when trying to index a non-array value. ```text PATH_TYPE_MISMATCH: Cannot index non-array value Location: path ["config", "settings", 0] Expected: array value for index access Found: string "development" Context: {"config": {"settings": "development"}} ``` -------------------------------- ### Multiset Diffing Example Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Shows multiset diffing which tracks element frequencies to find differences. Changes are generated based on frequency counts, including additions and removals. ```plaintext ^ "MULTISET" A: [1, 1, 2, 3] → {1:2, 2:1, 3:1} B: [1, 2, 2, 4] → {1:1, 2:2, 4:1} Changes: - 1 (reduce frequency 2→1) - 3 (remove entirely) + 2 (increase frequency 1→2) + 4 (add new) ``` -------------------------------- ### Example Path Resolution Error Source: https://github.com/josephburnett/jd/blob/master/spec/errors.md Demonstrates a path resolution error where the provided path attempts to access an array with a non-numeric index, leading to a type mismatch. ```text Document: {"users": [{"name": "Alice"}]} Path: ["users", "invalid_index", "name"] Error: PATH_TYPE_MISMATCH: Expected array index, got string "invalid_index" at path ["users"] ``` -------------------------------- ### Example Patch Context Mismatch Source: https://github.com/josephburnett/jd/blob/master/spec/errors.md Shows a patch application error where the expected context in an array does not match the document's content, preventing the patch from being applied. ```text Document: ["a", "b", "c"] Diff: @ [1] [ "x" <- Expected context "x", found "a" ✗ - "y" <- Expected "b", attempting to remove + "z" ] Error: PATCH_CONTEXT_MISMATCH: Expected context "x" at path [0], found "a" ``` -------------------------------- ### Build the Reference Test Runner Source: https://github.com/josephburnett/jd/blob/master/spec/test/README.md Compile the Go tool to create the executable binary. Ensure you are in the project's root directory. ```bash go build -o test-runner . ``` -------------------------------- ### Nested Set with Path Options in JD Diff Source: https://github.com/josephburnett/jd/blob/master/README.md Illustrates a diff on a nested set structure, where path options are used to target specific elements. This example shows additions and removals within a set of projects. ```diff @ ["department","employees",{"employeeId":"E123"},"projects",{}] - "ProjectA" + "ProjectB" + "ProjectC" ``` -------------------------------- ### Build and Run Reference Test Runner Source: https://github.com/josephburnett/jd/blob/master/spec/README.md Builds the Go reference test runner and executes it against a specified binary. Ensure you are in the 'test/' directory. ```bash cd test go build -o test-runner . ./test-runner /path/to/your/binary ``` -------------------------------- ### Serve jd Web UI Source: https://github.com/josephburnett/jd/blob/master/README.md Run the `jd` web UI locally on a specified port. ```bash jd -port 8080 ``` -------------------------------- ### Turn off diffing for specific field Source: https://github.com/josephburnett/jd/blob/master/doc/diff-on-off.md Example of turning off diffing for the `metadata.timestamp` field. ```json [{"@":["metadata","timestamp"],"^":["DIFF_OFF"]}] ``` -------------------------------- ### JSON for Sets with Non-String ID Keys Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Example of representing sets with non-string ID keys in JSON. ```json [[[{"one":"two"}]]] ``` -------------------------------- ### Run Tests with Make Source: https://github.com/josephburnett/jd/blob/master/CLAUDE.md Use the Makefile target 'test' to run all unit tests. This ensures project-specific build concerns are handled. ```bash make test ``` -------------------------------- ### Run Fuzz Tests with Make Source: https://github.com/josephburnett/jd/blob/master/CLAUDE.md Initiate fuzz testing for the project using the 'fuzz' target in the Makefile. This helps uncover edge cases and potential bugs. ```bash make fuzz ``` -------------------------------- ### Run All Unit Tests Source: https://github.com/josephburnett/jd/blob/master/doc/immutability.md Execute all unit tests within the v2 directory to ensure basic functionality. ```bash go test ./v2/ ``` -------------------------------- ### DIFF_OFF Option Example Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Applies the 'DIFF_OFF' option to ignore changes at a specified path, useful for fields like timestamps. ```JSON ^ {"@": ["metadata"], "^": ["DIFF_OFF"]} ``` -------------------------------- ### Allow-list Approach: Ignore all except userdata Source: https://github.com/josephburnett/jd/blob/master/doc/diff-on-off.md Demonstrates an allow-list approach by first turning off diffing for the entire document and then selectively turning it back on for the `userdata` path. ```json [ {"@":[],"^":["DIFF_OFF"]}, {"@":["userdata"],"^":["DIFF_ON"]} ] ``` -------------------------------- ### Format Go Code with Make Source: https://github.com/josephburnett/jd/blob/master/CLAUDE.md Apply Go code formatting using the 'go-fmt' target in the Makefile. This ensures consistent code style across the project. ```bash make go-fmt ``` -------------------------------- ### Run Spec Tests with Make Source: https://github.com/josephburnett/jd/blob/master/CLAUDE.md Execute the specification tests using the 'spec-test' target from the Makefile. This validates the implementation against the defined specification. ```bash make spec-test ``` -------------------------------- ### Basic Usage of Test Runner Source: https://github.com/josephburnett/jd/blob/master/spec/test/README.md Execute the test runner against a specified CLI binary. The first argument is the path to the binary under test. ```bash ./test-runner /path/to/jd ``` -------------------------------- ### JD v2 Diff with Options Header Source: https://github.com/josephburnett/jd/blob/master/README.md Shows how options used to create a diff are displayed at the beginning. This helps in understanding comparison parameters like array handling and number precision. ```diff ^ "SET" ^ {"precision":0.001} @ ["items",{}] - "old-item" + "new-item" ``` -------------------------------- ### Check for Vulnerabilities Source: https://github.com/josephburnett/jd/blob/master/CLAUDE.md Periodically run 'govulncheck ./...' to identify vulnerabilities in standard library and project dependencies. ```bash govulncheck ./... ``` -------------------------------- ### Read and Write YAML Source: https://github.com/josephburnett/jd/blob/master/README.md Use the `-yaml` option to process input and output as YAML instead of JSON. ```bash jd -yaml ``` -------------------------------- ### Configure JD as Git Diff Driver Source: https://github.com/josephburnett/jd/blob/master/README.md Provides instructions for setting up JD as a custom diff driver in Git. This allows for integrated structural diffing of JSON files directly within Git. ```bash # One-time setup git config diff.jd.command 'jd --git-diff-driver' echo "*.json diff=jd" >> .gitattributes ``` -------------------------------- ### DIFF_OFF Example for Metadata Source: https://github.com/josephburnett/jd/blob/master/spec/examples.md Disables diffing for a specific path (e.g., 'metadata') using 'DIFF_OFF'. Useful for excluding fields that change frequently but are not relevant for the diff. ```json { "data": {"value": 42}, "metadata": { "timestamp": "2023-01-01T10:00:00Z", "version": "1.0" } } ``` ```json { "data": {"value": 43}, "metadata": { "timestamp": "2023-01-02T11:00:00Z", "version": "1.1" } } ``` ```diff ^ {"@":["metadata"],"^":["DIFF_OFF"]} @ ["data","value"] - 42 + 43 ``` -------------------------------- ### Initialize Go WebAssembly Runtime Source: https://github.com/josephburnett/jd/blob/master/v2/internal/web/assets/index.html This snippet initializes the Go WebAssembly runtime and loads the jd.wasm module. It's typically used in a web environment to enable the JD functionality. ```javascript const go = new Go(); WebAssembly.instantiateStreaming(fetch("jd.wasm"), go.importObject).then((result) => { go.run(result.instance); }); ``` -------------------------------- ### Benchmark Array Insert at Beginning Source: https://github.com/josephburnett/jd/blob/master/doc/performance.md Benchmarks the performance of inserting an element at the beginning of an array. This operation is expected to be costly with immutability due to the need to copy the entire array. ```go func BenchmarkPatch_Array_InsertAtBeginning(b *testing.B) { sizes := []int{100, 1000, 10000} for _, size := range sizes { b.Run(fmt.Sprintf("Size_%d", size), func(b *testing.B) { // Create array [0, 1, 2, ..., size-1] original := generateSequentialArray(size) // Create patch to insert element at position 0 diff := createInsertAtBeginningDiff() b.ResetTimer() for i := 0; i < b.N; i++ { result, _ := original.Patch(diff) _ = result } }) } } ``` -------------------------------- ### Allow-list with DIFF_OFF and DIFF_ON Source: https://github.com/josephburnett/jd/blob/master/spec/examples.md Demonstrates using 'DIFF_OFF' for most paths and 'DIFF_ON' for specific paths (e.g., 'userdata') within an allow-list configuration. Useful for selectively enabling or disabling diffing across a structure. ```json { "userdata": {"name": "Alice"}, "system": {"cpu": "high", "memory": "normal"}, "timestamp": "2023-01-01" } ``` ```json { "userdata": {"name": "Bob"}, "system": {"cpu": "low", "memory": "high"}, "timestamp": "2023-01-02" } ``` ```diff ^ {"@":[],"^":["DIFF_OFF"]} ^ {"@":["userdata"],"^":["DIFF_ON"]} @ ["userdata","name"] - "Alice" + "Bob" ``` -------------------------------- ### Benchmark with Memory Allocation Tracking Source: https://github.com/josephburnett/jd/blob/master/doc/performance.md A standard benchmark pattern that includes tracking memory allocations using b.ReportAllocs(). Use this to measure memory usage during operations. ```go func BenchmarkWithAllocs_Operation(b *testing.B) { // Setup data := generateTestData() b.ReportAllocs() // Track memory allocations b.ResetTimer() for i := 0; i < b.N; i++ { result := performOperation(data) _ = result // Prevent optimization } } ``` -------------------------------- ### ABNF Grammar for Metadata Lines Source: https://github.com/josephburnett/jd/blob/master/spec/jd-format.md Specifies the ABNF syntax for metadata lines in a structural diff, which are used to convey options or settings. These lines start with a caret symbol. ```abnf MetadataLine = "^" SP JsonValue CRLF ``` -------------------------------- ### Deny-list Approach: Allow all except system fields Source: https://github.com/josephburnett/jd/blob/master/doc/diff-on-off.md Demonstrates a deny-list approach by turning off diffing for specific system-generated fields (`metadata.generated`, `metadata.timestamp`) while allowing changes elsewhere. ```json [ {"@":["metadata","generated"],"^":["DIFF_OFF"]}, {"@":["metadata","timestamp"],"^":["DIFF_OFF"]} ] ``` -------------------------------- ### Array Context Example in Structural Diff Source: https://github.com/josephburnett/jd/blob/master/spec/jd-format.md Illustrates diffing within an array, showing surrounding elements for context. Useful for changes in lists where adjacent items are important for understanding. ```diff @ ["items",1] "apple" - "banana" + "blueberry" "cherry" ] ``` -------------------------------- ### Focus on Memory Allocation Patterns Source: https://github.com/josephburnett/jd/blob/master/doc/performance.md Makefile target to run benchmarks specifically focused on memory allocation patterns. It uses go test with -benchmem and runs multiple counts for consistency. ```makefile # Focus on memory allocation patterns benchmark-memory: cd v2 && go test -bench=BenchmarkWithAllocs -benchmem -count=5 -timeout=10m ``` -------------------------------- ### Type Conversion: Object to Array Source: https://github.com/josephburnett/jd/blob/master/spec/examples.md Demonstrates a diff that converts a JSON object into an array. This is useful when a data structure needs to change its fundamental type, for example, from a key-value map to a list. ```json {"data": {"x": 1, "y": 2}} ``` ```json {"data": [1, 2]} ``` ```diff @ ["data"] - {"x":1,"y":2} + [1,2] ``` -------------------------------- ### Object Matching with Single Key Source: https://github.com/josephburnett/jd/blob/master/spec/semantics.md Enables object-level comparison within arrays using a specified key for identity. This example shows diffing an 'age' property for objects matching on 'id'. ```plaintext ^ {"keys": ["id"]} A: [{"id": "user1", "name": "Alice", "age": 25}] B: [{"id": "user1", "name": "Alice", "age": 26}] Path: [{"id": "user1"}, "age"] # Match by id, diff age property Result: @ [{"id":"user1"},"age"] - 25 + 26 ``` -------------------------------- ### Merge Patch Metadata Example in JD Diff Source: https://github.com/josephburnett/jd/blob/master/README.md Includes merge patch metadata, indicating that merge semantics were applied. This is shown with a '^ {"Merge":true}' header before the diff hunk. ```diff ^ {"Merge":true} @ ["config"] - {"timeout":30,"retries":3} + {"timeout":60,"retries":5,"debug":true} ``` -------------------------------- ### Specify Custom Test Cases Directory Source: https://github.com/josephburnett/jd/blob/master/spec/test/README.md Provide a custom path to the directory containing test cases. Use the -cases flag. ```bash ./test-runner -cases /path/to/cases /path/to/jd ``` -------------------------------- ### JD PathOptions for Targeted Comparison Source: https://context7.com/josephburnett/jd/llms.txt Use PathOptions with '-opts' to specify comparison strategies for specific paths within the data. ```bash jd -opts='[{"@":["tags"],"^":["SET"]}]' a.json b.json ``` ```bash jd -opts='[{"@":["metadata"],"^":["DIFF_OFF"]}]' a.json b.json ``` -------------------------------- ### Run Baseline Performance Tests Source: https://github.com/josephburnett/jd/blob/master/doc/performance.md Makefile target to execute baseline performance tests. It runs Go tests for BenchmarkPatch, including memory profiling, with a specified timeout. ```makefile .PHONY: benchmark-baseline benchmark-memory benchmark-save # Run baseline performance tests before immutability benchmark-baseline: @echo "Running pre-immutability baseline benchmarks..." cd v2 && go test -bench=BenchmarkPatch -benchmem -count=3 -timeout=10m ``` -------------------------------- ### Metadata: Additive Version and Merge Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Demonstrates additive metadata where version and merge behavior are specified on separate lines. ```diff ^ {"version":2} ^ {"merge":true} @ ["foo"] - "bar" + "baz" ``` -------------------------------- ### Complex List Context in JD Diff Source: https://github.com/josephburnett/jd/blob/master/README.md Shows a diff within a nested list structure, preserving context lines around the changed element. The example includes a removed element and an added element within a list. ```diff @ ["matrix",1,2] [[1,2,3],[4,5,6]] - 6 + 9 [7,8,9] ] ``` -------------------------------- ### Array Patch Insert at Beginning Benchmark Source: https://github.com/josephburnett/jd/blob/master/doc/performance.md Benchmark results for array patch operations, specifically inserting at the beginning. Performance scales linearly with array size. ```plaintext BenchmarkPatch_Array_InsertAtBeginning: - Size 100: 1.0μs, 2KB allocated, 8 allocs - Size 1000: 4.7μs, 16KB allocated, 8 allocs - Size 3000: 17.2μs, 49KB allocated, 8 allocs ``` -------------------------------- ### Apply Patch from File Source: https://github.com/josephburnett/jd/blob/master/README.md Apply a patch file to another file using the `jd -p` option. ```bash jd -p patch a.json ``` -------------------------------- ### Advanced Path Options for Diff Source: https://github.com/josephburnett/jd/blob/master/README.md Use `-opts` to specify advanced options, such as treating specific array paths as sets. ```bash jd -opts='[{"@":["items"],"^":["SET"]}]' a.json b.json ``` -------------------------------- ### Basic JD Command Usage Source: https://context7.com/josephburnett/jd/llms.txt Standard commands for comparing files using JD. Use '-f merge' for JSON Merge Patch output. ```bash jd -f merge a.json b.json ``` ```bash jd -set a.json b.json ``` ```bash jd -mset a.json b.json ``` ```bash jd -setkeys id,name a.json b.json ``` ```bash jd -precision=0.001 a.json b.json ``` ```bash jd -color a.json b.json ``` ```bash jd -yaml config1.yaml config2.yaml ``` ```bash jd -p patch.jd original.json ``` ```bash jd -o diff.txt a.json b.json ``` -------------------------------- ### Run End-to-End Tests Source: https://github.com/josephburnett/jd/blob/master/doc/immutability.md Execute end-to-end tests for the v2 package, identified by the 'E2E' tag. ```bash go test ./v2/ -run "E2E" ``` -------------------------------- ### Check Code Coverage with Make Source: https://github.com/josephburnett/jd/blob/master/CLAUDE.md Generate code coverage reports by running the 'cover' target from the Makefile. It enforces 100% coverage on non-trivial code. ```bash make cover ``` -------------------------------- ### Input JSON Response A Source: https://github.com/josephburnett/jd/blob/master/spec/examples.md The first JSON response to be compared. This serves as the baseline. ```json { "status": "success", "data": { "users": [ {"id": 1, "name": "Alice", "last_login": "2023-01-01T10:00:00Z"}, {"id": 2, "name": "Bob", "last_login": "2023-01-01T11:00:00Z"} ], "total": 2, "page": 1 }, "metadata": { "request_id": "req-123", "timestamp": "2023-01-01T12:00:00Z" } } ``` -------------------------------- ### GitHub Action for Diff Source: https://github.com/josephburnett/jd/blob/master/README.md This GitHub Action demonstrates how to use `jd` to diff two files within a workflow and access the output. ```yaml - name: Diff A and B id: diff uses: josephburnett/jd@v2.1.2 with: args: a.json b.json - name: Print the diff run: echo '${{ steps.diff.outputs.output }}' - name: Check the exit code run: if [ "${{ steps.diff.outputs.exit_code }}" != "1" ]; then exit 1; fi ``` -------------------------------- ### Apply Specific Changes to Another Deployment Source: https://github.com/josephburnett/jd/blob/master/README.md Create a focused patch file containing only a specific change (e.g., CPU modification) and apply it to another deployment using kubectl patch. This allows for granular updates. ```bash # Create a focused patch file containing only the CPU change kubectl get deployment example -oyaml | jd -yaml -opts='[ {"@":["metadata"],"^":["DIFF_OFF"]}, {"@":["status"],"^":["DIFF_OFF"]} ]' a.yaml > cpu-patch kubectl patch deployment example2 --type json --patch "$(jd -t jd2patch cpu-patch)" ``` -------------------------------- ### Configure JD as Git Diff Driver Source: https://context7.com/josephburnett/jd/llms.txt Set up JD to provide structural diffs for JSON files directly within Git. ```bash git difftool -yx jd @ -- config.json ``` ```bash git config diff.jd.command 'jd --git-diff-driver' ``` ```bash echo "*.json diff=jd" >> .gitattributes ``` ```bash git diff config.json ``` -------------------------------- ### Metadata: Version 2 with Merge Source: https://github.com/josephburnett/jd/blob/master/doc/v2.md Applies metadata for version 2 and enables merge patch behavior. ```diff ^ {"version":2,"merge":true} @ ["foo"] - "bar" + "baz" ``` -------------------------------- ### Treat Array as Set using CLI Source: https://github.com/josephburnett/jd/blob/master/README.md Use the -opts flag with a JSON string to specify that a particular array path should be treated as a set, ignoring order and duplicates. This is useful when the order of elements in an array does not matter for comparison. ```bash jd -opts='[{"@":["tags"],"^":["SET"]}]' a.json b.json ``` -------------------------------- ### Parse YAML String to JsonNode Source: https://context7.com/josephburnett/jd/llms.txt Use `ReadYamlString` to parse YAML content into a `JsonNode`. This allows for diffing between YAML and JSON sources. Errors during parsing are handled. ```go package main import ( "fmt" jd "github.com/josephburnett/jd/v2" ) func main() { yaml := ` name: Alice scores: - 85 - 92 - 78 ` node, err := jd.ReadYamlString(yaml) if err != nil { panic(err) } // Convert YAML to JSON fmt.Println(node.Json()) // Output: {"name":"Alice","scores":[85,92,78]} // Render back as YAML fmt.Println(node.Yaml()) } ``` -------------------------------- ### Generate Sequential Array Helper Source: https://github.com/josephburnett/jd/blob/master/doc/performance.md Helper function to generate an array with sequential integer values. Used for creating consistent test data for benchmarks. ```go // Helper functions for consistent test data func generateSequentialArray(size int) JsonNode { data := make([]interface{}, size) for i := 0; i < size; i++ { data[i] = i } node, _ := NewJsonNode(data) return node } ```