在Go中有没有一种将JSON转换为其模式的方法?我需要比较2个JSON模板或架构,却找不到任何程序包或函数来执行相同操作-有人可以帮我吗?
Go的标准库中提供的json包为我们提供了我们需要的所有功能。对于任何JSON字符串,解析它的标准方法是:
import "encoding/json" //...
// ... myJsonString := `{"some":"json"}`
// `&myStoredVariable` is the address of the variable we want to store our // parsed data in
json.Unmarshal([]byte(myJsonString), &myStoredVariable)
//...
您可以看一下gjson library。它具有解析和获取未编组JSON的功能。您可以使用gjson
功能比较json结果。
[我认为您需要将它们递归unmarshal
(如果它们包含嵌套的json)到类似map[string]interface{}', and then loop through and compare the keys. There are some libraries mentioned on this question https://stackoverflow.com/a/42153666 which could be used to
将它们安全地解组的位置。
例如,您可以使用gabs库中的Exists
,同时遍历未编组映射中的键以查看其他映射中是否存在相同的键。
// From gabs library
// Exists checks whether a field exists within the hierarchy.
func (g *Container) Exists(hierarchy ...string) bool {
return g.Search(hierarchy...) != nil
}