Comprare json string in golang

huangapple go评论82阅读模式
英文:

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")
	}

huangapple
  • 本文由 发表于 2021年10月26日 23:12:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/69725670.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定