I am writing a simple Go program to consume a simple API. Some values are not correctly unmarshaling into my struct, and I have traced the issue to the invalid key names in the returned JSON object.
I can reproduce the issue with this code:
jsonStr := `{
"valid_json": "I'm Valid",
"invalid'json": "I should be valid, but I'm not"
}`
type result struct {
Valid string `json:"valid_json"`
Invalid string `json:"invalid'json"`
}
var res result
err := json.Unmarshal([]byte(jsonStr), &res)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Valid: %s
", res.Valid)
fmt.Printf("Invalid: %s
", res.Invalid)
The resulting output:
Valid: I'm Valid
Invalid:
My expected output:
Valid: I'm Valid
Invalid: I should be valid, but I'm not
I've tried options such as escaping the '
in the struct tag, but this either results in an error or it is just ignored. I've also looked into alternate methods but have come back empty-handed.
How would this issue be properly handled on my end? Would it be better to strip the '
before unmarshaling? Or is there some other way that I could accept the single quote?