I am attempting to unmarshal data in Golang and I'm finding a strange behaviour when some key of the Json object has an underscore (_
) in it.
To give an example:
package main
import (
"encoding/json"
"fmt"
)
func main() {
var jsonBlob = []byte(`{"name": "Quoll", "order": "Dasyuromorphia"}`)
type Animal struct {
Name string `json: "name"`
Order string `json: "order"`
}
var animal Animal
err := json.Unmarshal(jsonBlob, &animal)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", animal)
}
This runs wonderfully. However, if I change some key to include an underscore:
var jsonBlob = []byte(`{"name": "Quoll", "order_": "Dasyuromorphia"}`)
And I wanted this to be included into Animal.Order
, I am attempting:
type Animal struct {
Name string `json: "name"`
Order string `json: "order_"`
}
and I am failing miserably to read the data. How can I map arbirary keys to the element I want of my struct? Here's a link to the playground with the example.
It has nothing to do with the underscore. In a struct tag, you can't have a space between the colon and quote, e.g. json:"name"
. In the first (working) example, the json
tags are still ignored; it just happens that the automatic logic works with the field names. If you remove the space after the colon in the struct tags, it works as expected with the latter example.
See working example here: https://play.golang.com/p/QXdlVsi166
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With