We want to rename a JSON field value
to v
in production. Till all our users use the new struct, we would continue to get old JSON structs into our code. So we want to handle this as well.
If you notice, First
is the original structure, Second
is the new structure. To handle both these structures, I have created a MyStruct
and based on version
, I copy the OldValue
into Value
if m.Version <= 1 {
m.Value = m.OldValue
}
Is there a better way to handle this, instead of my code.
package main
import "fmt"
import "encoding/json"
import "log"
type First struct {
Version int `json:"version"`
Value int `json:"value"`
}
type Second struct {
Version int `json:"version"`
Value int `json:"v"`
}
type MyStruct struct {
Version int `json:"version"`
OldValue int `json:"value"`
Value int `json:"v"`
}
func main() {
oldValue := []byte(`{"version":1, "value":5}`)
newValue := []byte(`{"version":2, "v":7}`)
var m MyStruct
err := json.Unmarshal(newValue, &m)
if err != nil {
log.Fatal(err)
}
fmt.Println("New Struct")
fmt.Println(m.Value)
err = json.Unmarshal(oldValue, &m)
if err != nil {
log.Fatal(err)
}
fmt.Println("Old Struct")
if m.Version <= 1 {
m.Value = m.OldValue
}
fmt.Println(m.Value)
}