daq – Data Queries
Access nested properties in Go data structures.
Go code for working with dynamic data structures can sometimes become somewhat verbose. E.g. like this:
var data any
json.Unmarshal([]byte(`{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"GlossTerm": "Standard Generalized Markup Language"
}
}
}
}
}`), &data)
title := "-no title-"
jObj, ok := data.(map[string]any)
if !ok {
fmt.Println(title)
return
}
if data = jObj["glossary"]; data == nil {
fmt.Println(title)
return
}
if jObj, ok = data.(map[string]any); !ok {
fmt.Println(title)
return
}
if data = jObj["title"]; data == nil {
fmt.Println(title)
return
}
title, _ = data.(string)
fmt.Println(title)
Package daq helps for example to make it much more concise:
var data any
json.Unmarshal([]byte(`{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"GlossTerm": "Standard Generalized Markup Language"
}
}
}
}
}`), &data)
title := StringOr("-no title-")(Get(data, "glossary", "title"))
fmt.Println(title)
In addition, daq can do even more, e.g. evaluate static data structures with the same API, iterate
and … please consult the reference.