0

I want to put my map data to another map data using Golang. however it has struct type.

Here is my code.

birth := make(map[string]interface{})

birth["docType"] = "registerBirth"
birth["agencyCd"] = string(args[0])
birth["birthYmd"] = string(args[1])
birth["lsTypeNm"] = string(args[2])
birth["monthDiff"] = string(args[3])
birth["nationNm"] = string(args[4])
birth["sexNm"] = string(args[5])
birth["regType"] = string(args[9])
birth["regYmd"] = string(args[10])

I want to put this map data to another map but I want to use struct type.

cattle := make(map[string]interface{})

cattle["docType"] = "information"
cattle["birthInfo"] = struct {
    birth map[string]interface{}
}{
    birth,
}

but, when I get data.. It comes out like this.

{"birthInfo":{},"docType":"information"}

Here Is the example that I want.

"birthInfo": {
        "birthYmd": "2018-07-25",
        "cattleNo": "cow001",
        "docType": "registerBirth",
        "farmNo": "farm001",
        "flatEartagNo": "eartag123123",
        "lsTypeNm": "황소",
        "monthDiff": "2018-07",
        "nationNm": "austria",
        "regType": "직접",
        "regYmd": "20185-07-25",
        "sexNm": "M"
    },
"docType": "information",
...

Thanks in advance.

TH Cho
  • 61
  • 5
  • Are you using some package to marshal or format your map? It can be because `birth` is an unexported field and thus not shown. I cannot reproduce the problem on playground using `fmt`. – leaf bebop Jul 31 '18 at 03:56
  • code works fine, check your args – CallMeLoki Jul 31 '18 at 07:11

1 Answers1

0

The problem is with this section of code

cattle["birthInfo"] = struct {
    birth map[string]interface{}
}{
    birth,
}

The json package can only marshal values that are exported (public / start with a capital letter).

Change the code block to this and it will work:

cattle["birthInfo"] = struct {
    Birth map[string]interface{} // note: capital "Birth", exported
}{
    birth,
}

Runnable example with exported field name:

https://play.golang.org/p/maTKn95AoGM

Zak
  • 5,515
  • 21
  • 33