I want to remove elements with empty value in struct. My script is below. Output of this script is {"keyA":{}}
. I used omitempty
to KeyA and KeyB. But an element with empty value is left. On the other hand KeyB is not shown. I want to show KeyA when it has values. I don't want to show KeyA when it has no values. Is there way to do this?
Script
package main
import (
"encoding/json"
"fmt"
)
type sample struct {
KeyA struct {
Key1 string `json:"keyA1,omitempty"`
Key2 string `json:"keyA2,omitempty"`
} `json:"keyA,omitempty"`
KeyB string `json:"keyB,omitempty"`
}
func main() {
var s sample
response, _ := json.Marshal(s)
fmt.Println(string(response)) // {"keyA":{}}
}
Thank you so much for your time. And I'm sorry for my immature question.