### Install Go JSON Diff Library Source: https://github.com/yudai/gojsondiff/blob/master/README.md Use 'go get' to install the gojsondiff library. This is the initial step before using the library in your Go projects. ```sh go get github.com/yudai/gojsondiff ``` -------------------------------- ### Install Go JSON Diff CLI Tool Source: https://github.com/yudai/gojsondiff/blob/master/README.md Install the 'jd' command-line tool using 'go get'. This tool allows you to compare JSON files directly from your terminal. ```sh go get github.com/yudai/gojsondiff/jd ``` -------------------------------- ### Install and Use JSON Patch CLI (jp) Source: https://context7.com/yudai/gojsondiff/llms.txt Installs the `jp` CLI tool for applying a delta file to a JSON file. Produces the patched JSON output. ```bash # Install the CLI tool go get github.com/yudai/gojsondiff/jp # Apply a delta patch to a JSON file jp delta.json original.json # Example: Given original.json: # {"name": "Alice", "score": 100} # # And delta.json: # {"score": [100, 150], "level": [5]} # # Output: # { # "level": 5, # "name": "Alice", ``` -------------------------------- ### Install and Use JSON Diff CLI (jd) Source: https://context7.com/yudai/gojsondiff/llms.txt Installs the `jd` CLI tool for comparing JSON files. Supports ASCII and delta output formats, with options for color and quiet mode. ```bash # Install the CLI tool go get github.com/yudai/gojsondiff/jd # Basic usage - compare two JSON files jd original.json modified.json # Output in ASCII format (default): # { # "name": "test", # - "value": 10 # + "value": 20 # + "new_field": "added" # } # Output in delta format (jsondiffpatch compatible) jd -f delta original.json modified.json # Output: # { # "new_field": ["added"], # "value": [10, 20] # } # Enable colored output (for terminals) jd -c original.json modified.json # Quiet mode - suppress output if no differences jd -q original.json modified.json ``` -------------------------------- ### JSON Diff Output Example Source: https://github.com/yudai/gojsondiff/blob/master/README.md Example of the default diff output format when comparing two JSON files using the 'jd' CLI tool. It highlights additions, deletions, and modifications. ```diff { "arr": [ 0: "arr0", 1: 21, 2: { "num": 1, - "str": "pek3f" + "str": "changed" }, 3: [ 0: 0, - 1: "1" + 1: "changed" ] ], "bool": true, "num_float": 39.39, "num_int": 13, "obj": { "arr": [ 0: 17, 1: "str", 2: { - "str": "eafeb" + "str": "changed" } ], + "new": "added", - "num": 19, "obj": { - "num": 14, + "num": 9999 - "str": "efj3" + "str": "changed" }, "str": "bcded" }, "str": "abcde" } ``` -------------------------------- ### JSON Diff Delta Format Output Example Source: https://github.com/yudai/gojsondiff/blob/master/README.md Example of the diff output in delta format, generated using the '-f delta' option with the 'jd' CLI tool. This format is compatible with jsondiffpatch. ```json { "arr": { "2": { "str": [ "pek3f", "changed" ] }, "3": { "1": [ "1", "changed" ], "_t": "a" }, "_t": "a" }, "obj": { "arr": { "2": { "str": [ "eafeb", "changed" ] }, "_t": "a" }, "new": [ "added" ], "num": [ 19, 0, 0 ], "obj": { "num": [ 14, 9999 ], "str": [ "efj3", "changed" ] } } } ``` -------------------------------- ### DeltaFormatter.FormatAsJson - Get Delta as Go Map Source: https://context7.com/yudai/gojsondiff/llms.txt Returns the delta as a Go map instead of a JSON string, useful for further programmatic manipulation. Access delta values by iterating over the returned map. ```go package main import ( "fmt" diff "github.com/yudai/gojsondiff" "github.com/yudai/gojsondiff/formatter" ) func main() { leftJSON := []byte(`{"status": "pending", "priority": 1}`) rightJSON := []byte(`{"status": "complete", "priority": 2}`) differ := diff.New() d, _ := differ.Compare(leftJSON, rightJSON) f := formatter.NewDeltaFormatter() deltaMap, _ := f.FormatAsJson(d) // Access delta values programmatically for key, value := range deltaMap { fmt.Printf("Field '%s' changed: %v\n", key, value) } // Output: // Field 'priority' changed: [1 2] // Field 'status' changed: [pending complete] } ``` -------------------------------- ### Full JSON Diff and Patch Cycle in Go Source: https://context7.com/yudai/gojsondiff/llms.txt Demonstrates a complete workflow: comparing two JSON documents, displaying an ASCII diff, generating a storable delta format, loading the delta, and applying the patch to reconstruct the target JSON. ```go package main import ( "encoding/json" "fmt" diff "github.com/yudai/gojsondiff" "github.com/yudai/gojsondiff/formatter" ) func main() { // Step 1: Define source and target JSON sourceJSON := []byte(`{ "version": "1.0", "config": { "debug": false, "timeout": 30, "endpoints": ["api.example.com"] }, "features": ["auth", "logging"] }`) targetJSON := []byte(`{ "version": "2.0", "config": { "debug": true, "timeout": 60, "endpoints": ["api.example.com", "backup.example.com"], "retries": 3 }, "features": ["auth", "logging", "caching"] }`) // Step 2: Compare JSON documents differ := diff.New() d, err := differ.Compare(sourceJSON, targetJSON) if err != nil { fmt.Printf("Compare error: %s\n", err) return } // Step 3: Display human-readable diff var sourceObj map[string]interface{}/ json.Unmarshal(sourceJSON, &sourceObj) asciiFormatter := formatter.NewAsciiFormatter(sourceObj, formatter.AsciiFormatterConfig{ ShowArrayIndex: true, Coloring: false, }) asciiDiff, _ := asciiFormatter.Format(d) fmt.Println("=== ASCII Diff ===") fmt.Println(asciiDiff) // Step 4: Generate storable delta format deltaFormatter := formatter.NewDeltaFormatter() deltaJSON, _ := deltaFormatter.Format(d) fmt.Println("=== Delta JSON ===") fmt.Println(deltaJSON) // Step 5: Later, load delta and apply patch um := diff.NewUnmarshaller() loadedDiff, _ := um.UnmarshalString(deltaJSON) // Apply to a fresh copy of source var freshSource map[string]interface{} json.Unmarshal(sourceJSON, &freshSource) differ.ApplyPatch(freshSource, loadedDiff) // Step 6: Verify result matches target result, _ := json.MarshalIndent(freshSource, "", " ") fmt.Println("=== Patched Result ===") fmt.Println(string(result)) } ``` -------------------------------- ### New - Create a Differ Instance Source: https://context7.com/yudai/gojsondiff/llms.txt Creates a new Differ instance with default configuration. The Differ is the main entry point for comparing JSON objects and applying patches. ```APIDOC ## New - Create a Differ Instance ### Description Creates a new Differ instance with default configuration. The Differ is the main entry point for comparing JSON objects and applying patches. ### Method N/A (Constructor) ### Endpoint N/A ### Request Example ```go package main import ( "fmt" diff "github.com/yudai/gojsondiff" ) func main() { // Create a new Differ instance differ := diff.New() // The differ is now ready for comparing JSON objects fmt.Printf("Differ created: %+v\n", differ) } ``` ### Response Example ```json { "example": "Differ created: &diff.differ{}" } ``` ``` -------------------------------- ### Create a New Differ Instance in Go Source: https://context7.com/yudai/gojsondiff/llms.txt Instantiate the main Differ object for JSON comparison. This is the primary entry point for using the library's programmatic API. ```go package main import ( "fmt" diff "github.com/yudai/gojsondiff" ) func main() { // Create a new Differ instance differ := diff.New() // The differ is now ready for comparing JSON objects fmt.Printf("Differ created: %+v\n", differ) } ``` -------------------------------- ### Compare JSON Files with JD CLI (Delta Format) Source: https://github.com/yudai/gojsondiff/blob/master/README.md Use the 'jd' command with the '-f delta' option to output differences in the jsondiffpatch delta format. This format is useful for programmatic patching. ```sh jd -f delta one.json another.json ``` -------------------------------- ### Compare JSON Files with JD CLI Source: https://github.com/yudai/gojsondiff/blob/master/README.md Use the 'jd' command to compare two JSON files. The output shows the differences in a human-readable format. ```sh jd one.json another.json ``` -------------------------------- ### Apply Patch with JP CLI Source: https://github.com/yudai/gojsondiff/blob/master/README.md Use the 'jp' command to apply a diff file (in delta format) to a JSON file. This reconstructs the target JSON from the source and the diff. ```sh jp diff.delta one.json ``` -------------------------------- ### Compare JSON Byte Slices in Go Source: https://context7.com/yudai/gojsondiff/llms.txt Compare two JSON documents represented as byte slices. This function returns a Diff object detailing the differences or an error if the JSON is malformed. ```go package main import ( "encoding/json" "fmt" diff "github.com/yudai/gojsondiff" ) func main() { // Original JSON left := []byte(`{ "name": "Alice", "age": 30, "city": "New York" }`) // Modified JSON right := []byte(`{ "name": "Alice", "age": 31, "city": "Boston", "country": "USA" }`) differ := diff.New() d, err := differ.Compare(left, right) if err != nil { fmt.Printf("Error comparing JSON: %s\n", err) return } // Check if there are any differences if d.Modified() { fmt.Println("JSON objects are different") fmt.Printf("Number of deltas: %d\n", len(d.Deltas())) // Output: // JSON objects are different // Number of deltas: 3 } else { fmt.Println("JSON objects are identical") } } ``` -------------------------------- ### Compare JSON Arrays in Go Source: https://context7.com/yudai/gojsondiff/llms.txt Compare two JSON arrays to detect additions, deletions, modifications, and moves within them. Useful for tracking changes in ordered data structures. ```go package main import ( "fmt" diff "github.com/yudai/gojsondiff" ) func main() { left := []interface{}{ "apple", "banana", "cherry", map[string]interface{}{"name": "item1", "value": 10}, } right := []interface{}{ "apple", "blueberry", // modified "cherry", map[string]interface{}{"name": "item1", "value": 20}, // nested modification "date", // added } differ := diff.New() d := differ.CompareArrays(left, right) fmt.Printf("Arrays modified: %t\n", d.Modified()) fmt.Printf("Number of changes: %d\n", len(d.Deltas())) // Output: // Arrays modified: true // Number of changes: 3 } ``` -------------------------------- ### AsciiFormatter - Human-Readable Diff Output Source: https://context7.com/yudai/gojsondiff/llms.txt Formats a Diff as human-readable ASCII output with '+' for additions and '-' for deletions. Supports optional colorization for terminal output. Configure ShowArrayIndex to true to display array indices. ```go package main import ( "encoding/json" "fmt" diff "github.com/yudai/gojsondiff" "github.com/yudai/gojsondiff/formatter" ) func main() { leftJSON := []byte(`{ "name": "John", "age": 30, "city": "NYC", "hobbies": ["reading", "gaming"] }`) rightJSON := []byte(`{ "name": "John", "age": 31, "city": "Boston", "hobbies": ["reading", "cooking"], "email": "john@example.com" }`) differ := diff.New() d, _ := differ.Compare(leftJSON, rightJSON) // Parse left JSON for formatter context var leftObj map[string]interface{} json.Unmarshal(leftJSON, &leftObj) // Configure ASCII formatter config := formatter.AsciiFormatterConfig{ ShowArrayIndex: true, // Show array indices in output Coloring: false, // Set true for terminal colors } f := formatter.NewAsciiFormatter(leftObj, config) output, _ := f.Format(d) fmt.Println(output) // Output: // { // "age": 30, // - "age": 30 // + "age": 31 // "city": "NYC", // - "city": "NYC" // + "city": "Boston" // + "email": "john@example.com", // "hobbies": [ // 0: "reading", // - 1: "gaming" // + 1: "cooking" // ], // "name": "John" // } } ``` -------------------------------- ### Compare - Compare JSON Byte Slices Source: https://context7.com/yudai/gojsondiff/llms.txt Compares two JSON documents provided as byte slices and returns a Diff object containing all detected deltas. Returns an error if the JSON is malformed. ```APIDOC ## Compare - Compare JSON Byte Slices ### Description Compares two JSON documents provided as byte slices and returns a Diff object containing all detected deltas. Returns an error if the JSON is malformed. ### Method `Compare` ### Endpoint N/A (Method of Differ instance) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A (Input is via function arguments) ### Request Example ```go package main import ( "encoding/json" "fmt" diff "github.com/yudai/gojsondiff" ) func main() { // Original JSON left := []byte(`{ "name": "Alice", "age": 30, "city": "New York" }`) // Modified JSON right := []byte(`{ "name": "Alice", "age": 31, "city": "Boston", "country": "USA" }`) differ := diff.New() d, err := differ.Compare(left, right) if err != nil { fmt.Printf("Error comparing JSON: %s\n", err) return } // Check if there are any differences if d.Modified() { fmt.Println("JSON objects are different") fmt.Printf("Number of deltas: %d\n", len(d.Deltas())) } else { fmt.Println("JSON objects are identical") } } ``` ### Response #### Success Response (200) - **Diff** (object) - An object containing the differences between the two JSON documents. #### Response Example ```json { "example": "JSON objects are different\nNumber of deltas: 3" } ``` ``` -------------------------------- ### Compare JSON Objects and Process Deltas in Go Source: https://context7.com/yudai/gojsondiff/llms.txt Compares two JSON objects and iterates through the resulting deltas, identifying Added, Deleted, Modified, Object, and Array changes. ```go package main import ( "fmt" diff "github.com/yudai/gojsondiff" ) func main() { left := map[string]interface{}{ "name": "Product", "price": 100, "category": "electronics", "details": map[string]interface{}{ "weight": 500, "color": "black", }, } right := map[string]interface{}{ "name": "Product Pro", // modified "price": 150, // modified // category deleted "details": map[string]interface{}{ "weight": 450, // nested modification "color": "silver", // nested modification }, "inStock": true, // added } differ := diff.New() d := differ.CompareObjects(left, right) // Process each delta by type for _, delta := range d.Deltas() { switch v := delta.(type) { case *diff.Added: fmt.Printf("ADDED at '%s': %v\n", v.PostPosition(), v.Value) case *diff.Deleted: fmt.Printf("DELETED at '%s': %v\n", v.PrePosition(), v.Value) case *diff.Modified: fmt.Printf("MODIFIED at '%s': %v -> %v\n", v.PostPosition(), v.OldValue, v.NewValue) case *diff.Object: fmt.Printf("OBJECT changed at '%s' with %d nested deltas\n", v.PostPosition(), len(v.Deltas)) case *diff.Array: fmt.Printf("ARRAY changed at '%s' with %d nested deltas\n", v.PostPosition(), len(v.Deltas)) } } // Output: // DELETED at 'category': electronics // OBJECT changed at 'details' with 2 nested deltas // ADDED at 'inStock': true // MODIFIED at 'name': Product -> Product Pro // MODIFIED at 'price': 100 -> 150 } ``` -------------------------------- ### Unmarshal String to Diff Object in Go Source: https://context7.com/yudai/gojsondiff/llms.txt A convenience method to load a delta directly from a string. Useful for quick patching operations. ```go package main import ( "encoding/json" "fmt" diff "github.com/yudai/gojsondiff" ) func main() { deltaStr := `{"count": [1, 2], "status": ["inactive", "active"]}` original := map[string]interface{}{ "count": 1, "status": "inactive", } um := diff.NewUnmarshaller() d, _ := um.UnmarshalString(deltaStr) differ := diff.New() differ.ApplyPatch(original, d) result, _ := json.MarshalIndent(original, "", " ") fmt.Println(string(result)) // Output: // { // "count": 2, // "status": "active" // } } ``` -------------------------------- ### ApplyPatch - Apply Diff to JSON Object Source: https://context7.com/yudai/gojsondiff/llms.txt Applies a diff to a JSON object in-place, transforming it to match the target state. This is a destructive operation that modifies the original object. ```go package main import ( "encoding/json" "fmt" diff "github.com/yudai/gojsondiff" ) func main() { // Original object original := map[string]interface{}{ "name": "Product A", "price": 29.99, "inStock": true, "tags": []interface{}{"electronics", "sale"}, } // Target state target := map[string]interface{}{ "name": "Product A", "price": 24.99, // price changed "inStock": false, // stock status changed "tags": []interface{}{"electronics", "clearance"}, // tag changed "discount": 0.15, // new field added } differ := diff.New() d := differ.CompareObjects(original, target) // Apply the patch to transform original -> target differ.ApplyPatch(original, d) // Verify the result result, _ := json.MarshalIndent(original, "", " ") fmt.Println(string(result)) // Output: // { // "discount": 0.15, // "inStock": false, // "name": "Product A", // "price": 24.99, // "tags": [ // "electronics", // "clearance" // ] // } } ``` -------------------------------- ### Unmarshal Bytes to Diff Object in Go Source: https://context7.com/yudai/gojsondiff/llms.txt Loads a delta JSON from bytes into a Diff object for patching. Ensure the delta is in jsondiffpatch format. ```go package main import ( "encoding/json" "fmt" diff "github.com/yudai/gojsondiff" ) func main() { // Delta in jsondiffpatch format deltaJSON := []byte(`{ "name": ["Alice", "Alicia"], "score": [100, 150], "level": [5] }`) // Original object to patch original := map[string]interface{}{ "name": "Alice", "score": 100, } // Unmarshal the delta um := diff.NewUnmarshaller() d, err := um.UnmarshalBytes(deltaJSON) if err != nil { fmt.Printf("Error: %s\n", err) return } // Apply the patch differ := diff.New() differ.ApplyPatch(original, d) result, _ := json.MarshalIndent(original, "", " ") fmt.Println(string(result)) // Output: // { // "level": 5, // "name": "Alicia", // "score": 150 // } } ``` -------------------------------- ### DeltaFormatter - jsondiffpatch Compatible Format Source: https://context7.com/yudai/gojsondiff/llms.txt Formats a Diff in the delta format compatible with jsondiffpatch. This format is suitable for serialization, storage, and interoperability with JavaScript implementations. ```go package main import ( "fmt" diff "github.com/yudai/gojsondiff" "github.com/yudai/gojsondiff/formatter" ) func main() { leftJSON := []byte(`{ "title": "Hello", "count": 5, "items": ["a", "b", "c"] }`) rightJSON := []byte(`{ "title": "Hello World", "count": 10, "items": ["a", "d", "c"], "active": true }`) differ := diff.New() d, _ := differ.Compare(leftJSON, rightJSON) // Create delta formatter f := formatter.NewDeltaFormatter() output, _ := f.Format(d) fmt.Println(output) // Output: // { // "active": [ // true // ], // "count": [ // 5, // 10 // ], // "items": { // "1": [ // "b", // "d" // ], // "_t": "a" // }, // "title": [ // "Hello", // "Hello World" // ] // } } ``` -------------------------------- ### CompareObjects - Compare Parsed JSON Objects Source: https://context7.com/yudai/gojsondiff/llms.txt Compares two already-parsed JSON objects (map[string]interface{}) and returns a Diff object. Useful when you've already unmarshaled your JSON data. ```APIDOC ## CompareObjects - Compare Parsed JSON Objects ### Description Compares two already-parsed JSON objects (map[string]interface{}) and returns a Diff object. Useful when you've already unmarshaled your JSON data. ### Method `CompareObjects` ### Endpoint N/A (Method of Differ instance) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A (Input is via function arguments) ### Request Example ```go package main import ( "fmt" diff "github.com/yudai/gojsondiff" ) func main() { // Pre-parsed JSON objects left := map[string]interface{}{ "user": "john", "score": 100, "active": true, "tags": []interface{}{"admin", "user"}, } right := map[string]interface{}{ "user": "john", "score": 150, // modified "active": false, // modified "tags": []interface{}{"admin", "moderator"}, // modified "email": "john@example.com", // added } differ := diff.New() d := differ.CompareObjects(left, right) fmt.Printf("Modified: %t\n", d.Modified()) fmt.Printf("Deltas found: %d\n", len(d.Deltas())) // Iterate through deltas for _, delta := range d.Deltas() { switch delta.(type) { case *diff.Modified: m := delta.(*diff.Modified) fmt.Printf("Modified: %v -> %v\n", m.OldValue, m.NewValue) case *diff.Added: a := delta.(*diff.Added) fmt.Printf("Added: %v\n", a.Value) case *diff.Deleted: del := delta.(*diff.Deleted) fmt.Printf("Deleted: %v\n", del.Value) } } } ``` ### Response #### Success Response (200) - **Diff** (object) - An object containing the differences between the two JSON objects. #### Response Example ```json { "example": "Modified: true\nDeltas found: 4\nModified: true -> false\nModified: 100 -> 150\nAdded: john@example.com" } ``` ``` -------------------------------- ### CompareArrays - Compare JSON Arrays Source: https://context7.com/yudai/gojsondiff/llms.txt Compares two JSON arrays and returns a Diff object. Detects additions, deletions, modifications, and moves within arrays. ```APIDOC ## CompareArrays - Compare JSON Arrays ### Description Compares two JSON arrays and returns a Diff object. Detects additions, deletions, modifications, and moves within arrays. ### Method `CompareArrays` ### Endpoint N/A (Method of Differ instance) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A (Input is via function arguments) ### Request Example ```go package main import ( "fmt" diff "github.com/yudai/gojsondiff" ) func main() { left := []interface{}{ "apple", "banana", "cherry", map[string]interface{}{"name": "item1", "value": 10}, } right := []interface{}{ "apple", "blueberry", // modified "cherry", map[string]interface{}{"name": "item1", "value": 20}, // nested modification "date", // added } differ := diff.New() d := differ.CompareArrays(left, right) fmt.Printf("Arrays modified: %t\n", d.Modified()) fmt.Printf("Number of changes: %d\n", len(d.Deltas())) } ``` ### Response #### Success Response (200) - **Diff** (object) - An object containing the differences between the two JSON arrays. #### Response Example ```json { "example": "Arrays modified: true\nNumber of changes: 3" } ``` ``` -------------------------------- ### Compare Parsed JSON Objects in Go Source: https://context7.com/yudai/gojsondiff/llms.txt Compare two already unmarshaled JSON objects (map[string]interface{}). This is efficient when JSON data is already in memory. ```go package main import ( "fmt" diff "github.com/yudai/gojsondiff" ) func main() { // Pre-parsed JSON objects left := map[string]interface{}{ "user": "john", "score": 100, "active": true, "tags": []interface{}{"admin", "user"}, } right := map[string]interface{}{ "user": "john", "score": 150, // modified "active": false, // modified "tags": []interface{}{"admin", "moderator"}, // modified "email": "john@example.com", // added } differ := diff.New() d := differ.CompareObjects(left, right) fmt.Printf("Modified: %t\n", d.Modified()) fmt.Printf("Deltas found: %d\n", len(d.Deltas())) // Iterate through deltas for _, delta := range d.Deltas() { switch delta.(type) { case *diff.Modified: m := delta.(*diff.Modified) fmt.Printf("Modified: %v -> %v\n", m.OldValue, m.NewValue) case *diff.Added: a := delta.(*diff.Added) fmt.Printf("Added: %v\n", a.Value) case *diff.Deleted: del := delta.(*diff.Deleted) fmt.Printf("Deleted: %v\n", del.Value) } } // Output: // Modified: true // Deltas found: 4 // Modified: true -> false // Modified: 100 -> 150 // Added: john@example.com } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.