[Golang] map <-> struct <-> json

개발者·2022년 10월 5일
0

Golang

목록 보기
2/4

6월에 이직을 하게 되어서 회사 노션 블로그에는 글을 여러개 작성했는데, 정작 내 블로그는 방치를 했다.

반성하며 글을 남기기로 했는데, 어떤 주제로 남길까 하다가 최근에 코드를 작성하면서 map, struct, json 간의 convert를 할 일이 있었어서 이에 대해서 글을 남기고자 한다.

필요한 패키지는

  • encoding/json
  • github.com/mitchellh/mapstructure
  • github.com/fatih/structs

이다.


map to json

package main

import (
	"encoding/json"
	"log"
)

func main() {
	mPerson := map[string]interface{}{
		"name": "테스터",
		"age":  10,
	}
	jsonStrPerson, err := json.Marshal(mPerson)
	if err != nil {
		log.Fatal(err)
	}
}

위 코드를 수행하면 {"age":10,"name":"테스터"} 이 출력된다.
mPersonjson.Marshal() 을 이용해서 마샬링해서 바이트 슬라이스 jsonStrPerson 를 얻을 수 있다.


map to struct

map 자료형을 struct로 변경하기 위해서는 mapstructure 패키지를 사용하면 간편하다.

go get github.com/mitchellh/mapstructure

사용법은 아래와 같다.

package main

import (
	"log"
	"github.com/mitchellh/mapstructure"
)

type Person struct {
	Name string `mapstructure:"name" json:"name"`
	Age  uint32 `mapstructure:"age" json:"age"`
}

func main() {
	mPerson := map[string]interface{}{
		"Name": "테스터",
		"Age":  10,
	}
	person := &Person{}
	err := mapstructure.Decode(mPerson, &person)
	if err != nil {
		log.Fatal(err)
	}
}

mapstructure.Decode를 이용해서 mPersonperson 구조체로 디코딩 해준다.

json 태그 처럼 mapstructure 태그를 구조체 선언할 때 함께 선언하면 Decodemapkey값으로 매칭해서 찾아준다. 추가로 json 태그와 mapstructrue 태그는 대소문자를 구별하지 않기 때문에, 대소문자로 구별되어 있는 값이 있으면 처리에 유의해야 한다.


json to struct

package main

import (
	"encoding/json"
	"log"
)

type Person struct {
	Name string `json:"name"`
	Age  uint32 `json:"age"`
}

func main() {
	data := []byte("{\"Name\": \"테스터\", \"Age\": 10}")
	person := &Person{}

	err := json.Unmarshal(data, &person)
	if err != nil {
		log.Println(err)
	}
}

json.Unmarshal() 함수를 이용해서 json 데이터를 struct 데이터로 변경할 수 있다.


json to map

package main

import (
	"encoding/json"
	"log"
)

func main() {
	data := []byte("{\"Name\": \"테스터\", \"Age\": 10}")
	var mPerson map[string]interface{}

	err := json.Unmarshal(data, &mPerson)
	if err != nil {
		log.Println(err)
	}
}

json to struct와 마찬가지로 json.Unmarshal() 함수를 이용해서 json 데이터를 map 데이터로 변경할 수 있다.


struct to json

package main

import (
	"encoding/json"
	"log"
)

type Person struct {
	Name string `json:"name"`
	Age  uint32 `json:"age"`
}

func main() {
	person := &Person{Name: "테스터", Age: 10}

	jsonStrPerson, err := json.Marshal(person)
	if err != nil {
		log.Println(err)
	}
}

structjson 으로 변경하는 것은mapjson으로 변경하는 것 처럼 json.Marshal() 을 이용해서 마샬링 할 수 있다.

여기서 구조체 선언시 사용한 json태그를 이용하면 원하는대로 마샬링 할 수 있는데, 예를 들어

type Person struct {
	Name string `json:"foo"`
	Age  uint32 `json:"bar"`
}

이와 같이 json태그를 선언하고 마샬링 하면 {"foo":"테스터","bar":10}의 형태를 가진 json을 얻을 수 있다.


struct to map

structmap으로 바꾸기 위해서는 structs 패키지를 이용해 볼 수 있다.

go get github.com/fatih/structs
package main

import (
	"github.com/fatih/structs"
)

type Person struct {
	Name string
	Age  uint32
}

func main() {
	person := &Person{Name: "테스터", Age: 10}
	mapPerson := structs.Map(person)
}

마찬가지로 structs 태그를 이용해서 map으로 변환됐을 때 원하는 key값을 structs 태그를 이용해서 지정할 수 있다.

type Person struct {
	Name string `structs:"foo"`
	Age  uint32 `structs:"bar"`
}

reference

profile
solrasido

0개의 댓글