Files
be.ems/tools/compare/cmpjson.go
2025-05-23 18:24:18 +08:00

102 lines
2.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"encoding/json"
"fmt"
"reflect"
)
// CompareJSON 比较两个 JSON返回新增、修改和删除的内容
func CompareJSON(json1, json2 string) (map[string]interface{}, map[string]interface{}, map[string]interface{}, error) {
var map1, map2 map[string]interface{}
// 解析 JSON
if err := json.Unmarshal([]byte(json1), &map1); err != nil {
return nil, nil, nil, fmt.Errorf("failed to parse json1: %v", err)
}
if err := json.Unmarshal([]byte(json2), &map2); err != nil {
return nil, nil, nil, fmt.Errorf("failed to parse json2: %v", err)
}
// 存储新增、修改和删除的内容
added := make(map[string]interface{})
modified := make(map[string]interface{})
deleted := make(map[string]interface{})
// 递归比较
compareMaps(map1, map2, added, modified, deleted, "")
return added, modified, deleted, nil
}
// compareMaps 递归比较两个 map
func compareMaps(map1, map2, added, modified, deleted map[string]interface{}, prefix string) {
// 遍历 map1检查删除或修改
for key, val1 := range map1 {
fullKey := key
if prefix != "" {
fullKey = prefix + "." + key
}
val2, exists := map2[key]
if !exists {
// 如果 key 不存在于 map2记录为删除
deleted[fullKey] = val1
} else if !reflect.DeepEqual(val1, val2) {
// 如果 key 存在但值不同,记录为修改
if reflect.TypeOf(val1) == reflect.TypeOf(val2) && reflect.TypeOf(val1).Kind() == reflect.Map {
// 如果值是嵌套对象,递归比较
compareMaps(val1.(map[string]interface{}), val2.(map[string]interface{}), added, modified, deleted, fullKey)
} else {
modified[fullKey] = map[string]interface{}{
"old": val1,
"new": val2,
}
}
}
}
// 遍历 map2检查新增
for key, val2 := range map2 {
fullKey := key
if prefix != "" {
fullKey = prefix + "." + key
}
if _, exists := map1[key]; !exists {
// 如果 key 不存在于 map1记录为新增
added[fullKey] = val2
}
}
}
func main() {
json1 := `{
"name": "example",
"age": 25,
"address": {
"city": "New York",
"zip": "10001"
}
}`
json2 := `{
"name": "example",
"age": 26,
"address": {
"city": "Los Angeles"
},
"phone": "123-456-7890"
}`
added, modified, deleted, err := CompareJSON(json1, json2)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Added: %v\n", added)
fmt.Printf("Modified: %v\n", modified)
fmt.Printf("Deleted: %v\n", deleted)
}