Member-only story
Go: Nested Struct Marshall & UnMarshall
The journey of “struct to json” -> “json to struct”
Mapping your model object to the response JSON from an API or reading from an input file is a common scenario while building a distributed application using Go.
Let’s take an example to understand: We have a nested JSON sample response as input in our application. Input consists of an encrypted message and key. If you look closely encryption mechanism is Caesar cipher.
{
"sampleInput": {
"input": {
"encryptedMessage": "F KFRTZX JCUQTWJW TSHJ XFNI, YMFY YMJ JCYWFTWINSFWD NX NS BMFY BJ IT, STY BMT BJ FWJ. LT JCUQTWJ!",
"key": 5
}
}
}
Let us construct the model hierarchy for this input.
type input struct {
EncryptedMessage string `json:"encryptedMessage"`
Key int `json:"key"`
}type sampleInput struct {
Input input `json:"input"`
}type sample struct {
SampleInput sampleInput `json:"sampleInput"`
}
In this case, I am considering inputs from a local file.
Let’s UnMarshall it (using “encoding/json” module)
file, _ := ioutil.ReadFile("input-nested.json")var data sample
err := json.Unmarshal([]byte(file), &data)
if err != nil {
fmt.Println("error:", err)
}fmt.Println(data)