登录
首页 >  Golang >  Go问答

如何将 DynamoDB 中的映射解组为结构体?

来源:stackoverflow

时间:2024-04-16 18:45:32 414浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《如何将 DynamoDB 中的映射解组为结构体?》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

dynamo上有以下字段

{

      "config": {
        "base_auth_url_key": "https://auth.blab.bob.com",
        "base_url": "https://api.dummy.data.com",
        "conn_time_out_seconds": "300000",
        "read_time_out_seconds": "300000"
      },
      "id": "myconfig"
    }
and getting the element with dynamodbattribute

    import(
        "github.com/aws/aws-sdk-go/service/dynamodb"
        "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute")

    result, err := svc.getitem(&dynamodb.getiteminput{
        tablename: aws.string(tablename),
        key: map[string]*dynamodb.attributevalue{
            "id": {
                s: aws.string(configid),
            },
        },
    })

这段代码可以工作,但是当我尝试检索它呈现的对象时,它是这样的

map[config:{
      m: {
        base_auth_url_key: {
          s: "https://auth.blab.bob.com"
        },
        conn_time_out_seconds: {
          s: "300000"
        },
        read_time_out_seconds: {
          s: "300000"
        },
        base_url: {
          s: "https://api.dummy.data.com"
        }
      }
    } id:{
      s: "myconfig"
    }]

因此,当我尝试解组对象时,解组的对象返回为 {}

type Config struct {
    id                  string
    baseAuthUrlKey      string
    baseUrl             string
    connectTimeOutSecs  string
    readTimeOutSecs     string
}

item := Config{}
err = dynamodbattribute.UnmarshalMap(result.Item, &item)

如何将从 getitem 返回的值分配给我的结构,该值似乎是我的结构的映射?

解决方案


问题的根源是您的 config 结构的结构不正确。

在将 json 转换为 go 结构时,我建议使用 json-to-go;该工具将帮助您将来发现类似的问题。

一旦你正确构造了你的结构,你还会注意到你的结构字段没有大写,这意味着它们不会被导出(即能够被其他包使用),这是你的 unmarshalmap 代码将被导出的另一个原因没有返回您期望的结果。

Here 是关于结构体字段可见性及其重要性的一个很好的答案,上面简要总结了这一点。

下面是您的结构的更正版本,与您的 unmarshalmap 代码相结合,将正确地允许您打印您的 item 并且不会收到 {} ,这没有什么乐趣。

type Item struct {
    Config struct {
        BaseAuthUrlKey     string `json:"BASE_AUTH_URL_KEY"`
        BaseUrl            string `json:"BASE_URL"`
        ConnTimeoutSeconds string `json:"CONN_TIME_OUT_SECONDS"`
        ReadTimeoutSeconds string `json:"READ_TIME_OUT_SECONDS"`
    } `json:"config"`
    ID string `json:"id"`
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>