dictionary - 使用 Golang 将映射数据输入到结构中

标签 dictionary go

<分区>

我想使用 Golang 将我的 map 数据放入另一个 map 数据。但是它有结构类型。

这是我的代码。

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])

我想把这个 map 数据放到另一个 map 上,但是我想使用struct类型。

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

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

但是,当我得到数据时..结果是这样的。

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

这是我想要的例子。

"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",
...

提前致谢。

最佳答案

问题出在这段代码上

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

json 包只能编码导出的值(公共(public)/以大写字母开头)。

将代码块改成这样就可以了:

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

具有导出字段名称的可运行示例:

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

关于dictionary - 使用 Golang 将映射数据输入到结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51604587/

相关文章:

javascript - 多维字典中的二分查找?

ios - Swift - 解析嵌套 JSON 对象中的数组不起作用

c++ - 如何跟踪列表的更改

go - Go 语言中 getter 和 setter 的接口(interface)

object - 如何在 Go 中创建键值的枚举/映射

C# 字符串替换为字典

python - 在 Python 中,如何对元组、字典列表中的数字列表求和?

for-loop - "Select"goroutine 内的 for 循环语句

go - 我应该如何在 go 中导入自己的内部包?

struct - 使用结构传递多个值 GO