gpt4 book ai didi

json - 去测试 map 之间的区别

转载 作者:数据小太阳 更新时间:2023-10-29 03:27:04 26 4
gpt4 key购买 nike

我正在尝试对 json 对象运行一些测试。目前我有一个函数来比较 json 字符串并在它们不匹配时输出错误消息:

func assertJsonEqual(expected, actual string) bool {
actualStruct := make(map[string]interface{})
expectedStruct := make(map[string]interface{})

json.Unmarshal([]byte(expected), &expectedStruct)
json.Unmarshal([]byte(actual), &actualStruct)

if !reflect.DeepEqual(expectedStruct, actualStruct) {
log.Errorf("Expected: %#v\n but got %#v", expectedStruct, actualStruct)
return false
}
return true
}

问题在于,这使得在实际工具中很难准确地看到缺少或多余的键。我正在考虑构建映射键的简单差异,但想知道是否有一个现有的库已经这样做了?

最佳答案

没有一个现有的功能,就像 5 行代码。

diff := &[]string{} // initialize some storage for the diff

for _, k := range map1 { // range over one of the maps
if _, ok := map2[k]; !ok { // check if the key from the first map exists in the second
diff = append(diff, k)
}
}

关于json - 去测试 map 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37844810/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com