Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmarshal Json with space in custom struct tag [duplicate]

Tags:

json

go

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.

like image 362
adrpino Avatar asked Jan 29 '23 08:01

adrpino


1 Answers

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

like image 182
Adrian Avatar answered Feb 02 '23 09:02

Adrian