-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_diff.go
More file actions
65 lines (51 loc) · 1.46 KB
/
json_diff.go
File metadata and controls
65 lines (51 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package testastic
import (
"encoding/json"
"fmt"
"strings"
)
// formatJSONDiffInline generates a git-style inline diff between expected and actual JSON.
// Shows the full JSON with - prefix for removed lines and + prefix for added lines.
func formatJSONDiffInline(expected, actual any) string {
expClean := cleanMatchersForDisplay(expected)
actClean := cleanMatchersForDisplay(actual)
expJSON, err := json.MarshalIndent(expClean, "", " ")
if err != nil {
return fmt.Sprintf("error formatting expected: %v", err)
}
actJSON, err := json.MarshalIndent(actClean, "", " ")
if err != nil {
return fmt.Sprintf("error formatting actual: %v", err)
}
expLines := strings.Split(string(expJSON), "\n")
actLines := strings.Split(string(actJSON), "\n")
diff := computeDiff(expLines, actLines)
var sb strings.Builder
for _, line := range diff {
sb.WriteString(line)
sb.WriteString("\n")
}
return sb.String()
}
// cleanMatchersForDisplay converts Matcher objects to their string representation
// so they can be displayed in the diff output.
func cleanMatchersForDisplay(data any) any {
switch v := data.(type) {
case map[string]any:
result := make(map[string]any, len(v))
for key, val := range v {
result[key] = cleanMatchersForDisplay(val)
}
return result
case []any:
result := make([]any, len(v))
for i, val := range v {
result[i] = cleanMatchersForDisplay(val)
}
return result
case Matcher:
return v.String()
default:
return v
}
}