This question already has an answer here:
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.
</div>