LoginSignup
21
25

More than 5 years have passed since last update.

Go言語でstructをmapに変換する

Last updated at Posted at 2016-01-17

コード


package main

import (
    "fmt"
    "reflect"
    "encoding/json"
)

func StructToMap(data interface{}) map[string]interface{} {
  result := make(map[string]interface{})
  elem := reflect.ValueOf(data).Elem()
  size := elem.NumField()

  for i := 0; i < size; i++ {
    field := elem.Type().Field(i).Name
    value := elem.Field(i).Interface()
    result[field] = value
  }

  return result
}

func StructToJsonTagMap(data interface{}) map[string]interface{} {
  result := make(map[string]interface{})
  elem := reflect.ValueOf(data).Elem()
  size := elem.NumField()

  for i := 0; i < size; i++ {
    field := elem.Type().Field(i).Tag.Get("json")
    value := elem.Field(i).Interface()
    result[field] = value
  }

  return result
}

func StructToJsonTagMap2(data interface{}) map[string]interface{} {
  result := make(map[string]interface{})

  b, _ := json.Marshal(data)
  json.Unmarshal(b, &result)

  return result
}

type A struct {
    ID int `json:"id"`
    Name string `json:"name"`
}

func main() {
    a := A{1, "keitaj"}
    fmt.Println(a)

    b := StructToMap(&a)
    fmt.Println(b)

    c := StructToJsonTagMap(&a)
    fmt.Println(c)

    d := StructToJsonTagMap2(&a)
    fmt.Println(d)
}

実行結果

{1 keitaj}
map[ID:1 Name:keitaj]
map[id:1 name:keitaj]
map[name:keitaj id:1]

備考

Tagをmapのkeyにしたい場合は、StructTag型のGetメソッドを使う

参考記事

21
25
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
21
25