🐾 [golang] DB안에 JSON 객체를 넣는 방법(jsonb 사용)
# 배경
캠페인마다 약관을 넣어야 했다. 약관내용을 json 값으로 DB에 넣어야 한다고 했다. 시니어 개발자분의 힌트는 jsonb를 이용하라고 했다.
#방법
DB 컬럼하나에 JSON을 넣고 싶었다. 이럴 때에는 jsonb을 사용한다 xorm:“a jsonb” 이렇게 설정하면 된다
json 예시
"a": {
"aOne": "a객체안에 하나",
"b": {
"bOne": "a객체안에 b 객체안에 하나",
"bTwoArray": [
{
"name": "홍길동",
"content" : "객체안에 객체안에 배열"
}
]
},
"aThreeArray": [
{
"id": 1,
"content": "객체안에 배열"
},
{
"id":2,
"content": "객체안에 배열 2개"
}
]
}
# DTO에서 구조체
type ACreate struct {
A *A `json:"a" `
}
type A struct {
AOne string `json:"aOne" validate:"required" `
B B `json:"b" `
AThreeArray []AThreeArray `json:"aThreeArray"`
}
type B struct {
BOne string `json:"bOne"`
BTwoArray []BTwoArray `json:"bTwoArray"`
}
type BTwoArray struct {
CompanyName string `json:"companyName"`
Content string `json:"content"`
}
type AThreeArray struct {
Id string `json:"id" `
Content string `json:"content"`
}