I'm working on a Go API that can receive POSTs consisting of a JSON array of objects. The structure of the POST will look something like:
[
{
"name":"Las Vegas",
"size":14
},
{
"valid": false,
"name":"Buffalo",
"size":63
}
]
Let's say I have the following struct:
type Data {
Valid bool
Name string
Size float64
}
I want to create a bunch of Data
s with Valid
set to true
anytime it's not actually specified in the JSON as false
. If I were doing a single one I could use How to specify default values when parsing JSON in Go, but for doing an unknown number of them the only thing I've been able to come up with is something like:
var allMap []map[string]interface{}
var structs []Data
for _, item := range allMap {
var data Data
var v interface{}
var ok bool
if v, ok := item["value"]; ok {
data.Valid = v
} else {
data.Valid = true
}
id v, ok := item["name"]; ok {
data.Name = v
}
...
structs = append(structs, data)
}
return structs
Right now the struct I'm actually working with has 14 fields, some of them have values I want to assign defaults, others are fine to leave blank, but all of them have to be iterated through using this approach.
Is there a better way?