英文:
Comprare json string in golang
问题
我有两个JSON字符串要比较。我不知道如何做。
第一个字符串:
{"timestamp":"2021-10-26T15:09:35.322019337Z","prices":[{"country":"fr","price":{"recommended":0}},{"country":"at","price":{"recommended":0}},{"country":"de","price":{"recommended":0}}]} 
第二个字符串:
{"timestamp":"2021-10-26T15:09:35.322019337Z","prices":[{"country":"fr","price":{"recommended":0}},{"country":"de","price":{"recommended":0}},{"country":"at","price":{"recommended":0}}]}
你可以看到数组的顺序不同。
英文:
I have two JSON strings I want to compare. I don't know how to it
First string
{"timestamp":"2021-10-26T15:09:35.322019337Z","prices":[{"country":"fr","price":{"recommended":0}},{"country":"at","price":{"recommended":0}},{"country":"de","price":{"recommended":0}}]} 
Second string
{"timestamp":"2021-10-26T15:09:35.322019337Z","prices":[{"country":"fr","price":{"recommended":0}},{"country":"de","price":{"recommended":0}},{"country":"at","price":{"recommended":0}}]}
as you can see there is a different order in the array.
答案1
得分: 4
你可以对它们进行解组,并使用reflect.DeepEqual进行比较:
var v1, v2 interface{}
json.Unmarshal([]byte(s1), &v1)
json.Unmarshal([]byte(s2), &v2)
if reflect.DeepEqual(v1, v2) {
   // 它们是相同的
} else {
   // 它们是不同的
}
还有其他一些用于比较 JSON 的包可供使用。
英文:
You can unmarshal them, and use reflect.DeepEqual:
var v1, v2 interface{}
json.Unmarshal([]byte(s1),&v1)
json.Unmarshal([]byte(s2),&v2)
if reflect.DeepEqual(v1,v2) {
   // They are the same
} else {
   // They are different
}
There are also other JSON comparison packages out there.
答案2
得分: 2
这是一个比较字符串的简单方法:
	if strings.Compare(string1, string2) != 0 {
		return errors.New("字符串不匹配")
	}
英文:
Here's a simple method for comparing strings:
	if strings.Compare(string1, string2) != 0 {
		return errors.New("strings don't match")
	}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论