LoginSignup
6
5

More than 5 years have passed since last update.

Goのencoding/jsonでタグが反映されなくてハマったしょうもない話

Posted at

Goではstructを定義して、Marshalするとjsonに変換されますね。
例えば、

type Person struct {
    ID int
    Name string
    Email string
    Age int
    Address string
    memo string
}

person := &Person {
    ID: 1,
    Name: "Gopher",
    Email: "goher@example.com",
    Age: 5,
    Address: "",
}

p, err := json.Marshal(person)

こんな感じに

{
    "ID":1,
    "Name":"Gopher",
    "Email":"goher@example.com",
    "Age":5,
    "Address":""
}

出力されるkey名を変えたいときは、structの定義にタグを付ければいいのですが、
↓だと反映されない。。orz

type Person struct {
    ID int
    Name string `json: "name"`
    Email string
    Age int
    Address string
    memo string
}

なんでかというと、
タグのjson:"name"の間にスペースがあるから。

なんともしょうもない理由だけど、これ
コンパイル時にエラーにならないし、警告もでないからサクッと見過ごしてしまう。。

スペースを入れずに↓のようにすれば

type Person struct {
    ID int
    Name string `json:"name"`
    Email string
    Age int
    Address string
    memo string
}

しっかり反映される。

{
    "ID":1,
    "name":"Gopher",
    "Email":"goher@example.com",
    "Age":5,
    "Address":""
}

という、しょうもないハマりレポートでした。みんな気をつけよう!!

6
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5