简体   繁体   English

比较go中的两个JSON

[英]Comparing two JSON in go

I am trying to compare data in JSON format in Go. I just need to check if they have both have the same structure and not the values.我正在尝试比较 Go 中 JSON 格式的数据。我只需要检查它们是否具有相同的结构而不是值。 I was using the below code.我正在使用下面的代码。 tree and tree2 are JSON. However, if the keys are the same and the values are different, the below code shows as false, the expected answer should be true. tree 和 tree2 是 JSON。但是,如果键相同而值不同,则以下代码显示为 false,预期答案应该为 true。 I appreciate any help in the direction.我感谢方向上的任何帮助。

var a1  interface{}
var a2 interface{}
json.Unmarshal([]byte(tree), &a1)
json.Unmarshal([]byte(tree2), &a2)
fmt.Println(reflect.DeepEqual(a1,a2))

There is no easy way you can do this.没有简单的方法可以做到这一点。 You have to write a recursive comparison function, something like this:您必须编写一个递归比较函数,如下所示:

func compareKeys(in1,in2 interface{}) bool {
  if m1, ok:=in1.(map[string]interface{}); ok {
     if m2, ok:=in2.(map[string]interface{}); ok {
         return compareMaps(m1,m2)
     }
     return false
  }
  if a1,ok := in1.([]interface{}); ok {
    if a2, ok:=in2.([]interface{}); ok {
       return compareArrays(a1, a2);
    }
    return false
   }
  if _, ok:=in2.(map[string]interface{}); ok {
      return false
  }
  if _, ok:=in2.([]interface{}); ok {
      return false
  }
  return true
}

func compareMaps(in1, in2 map[string]interface{}) bool {
   if len(in1)!=len(in2) {
      return false
   }
   for k,v:=range in1 {
      if v2, ok:=in2[k]; ok {
         if !compareKeys(v, v2) {
             return false
          }
       } else {
          return false
       }
   }
   return true
}


func compareArrays(in1, in2 []interface{}) bool {
  if len(in1)!=len(in2) {
     return false
  }
  for i:=range in1 {
     if !compareKeys(in1[i],in2[i]) {
       return false
     } 
  }
  return true
}

You may compare jour strings like this: https://pkg.go.dev/github.com/stretchr/testify/require#JSONEqf您可以像这样比较 jour 字符串: https://pkg.go.dev/github.com/stretchr/testify/require#JSONEqf

if assert.JSONEqf(t, {"hello": "world", "foo": "bar"} , {"foo": "bar", "hello": "world"} , "error message %s", "formatted") { println("#############################################") }如果 assert.JSONEqf(t, {"hello": "world", "foo": "bar"} , {"foo": "bar", "hello": "world"} , "error message %s", “格式化”){ println(“########################################## ###") }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM