LoginSignup
32
14

More than 5 years have passed since last update.

【Golang】Structのタグを取得する方法

Last updated at Posted at 2019-01-21

概要

CSVファイルなどにStructのタグをヘッダー形式で書き込む際に
便利なStructタグの取得方法を紹介します。
今回はJsonファイルのキーを取得します。  

前提

このようなStructがあると仮定します。

// Information はJsonファイルの構造体
type Information struct {
    ID      int    `json:"id"`
    Title string `json:"title"`
    Date string `json:"date"`
}

Jsonファイルのイメージ

[
  {
    "id": 1,
    "title": "A - foo1",
    "date": "2019-01-01T00:00:00+09:00"
  },
  {
    "id": 2,
    "title": "B - foo2",
    "date": "2019-01-02T00:00:00+09:00"
  }
]

CSVファイルの場合、ヘッダーの完成図は

id, title, date 

上記のようなイメージになります。

実装

構造体の情報を取得する際に有用なreflectパッケージのTypeof関数を使って
Jsonファイルのタグを取得します。

reflect パッケージ - golang.jp

func main() {
    // Structのjsonタグを取得
    s := Information{}
    t := reflect.TypeOf(s)

    // 取得したjsonタグを格納するスライスを宣言
    var lenInfo []string

    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        j := field.Tag.Get("json")
        lenInfo = append(lenInfo, j)
    }

    // スライスをカンマ区切りの文字列に変換
    strInfo := strings.Join(lenInfo, ", ")

    fmt.Println(lenInfo) // 出力結果: [id title date]
    fmt.Println(strInfo) // 出力結果: id, title, date
}

以上がStructタグの取得方法となります。

おまけ

スライスであるlenInfoで取得した値を出力すると[id title date]
スライスのまま出力されてしまいます。
これではヘッダーとして格好がつきません。

ここでJoin関数を使って文字列に変換します。
ついでにカンマ区切りにしてしまいます。
strInfo := strings.Join(lenInfo, ", ")

出力結果はid, title, date
想定通りになりました。

strings パッケージ - golang.jp

32
14
0

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
32
14