【问题标题】:DynamoDB UnmarshalListOfMaps creates empty values in GoDynamoDB UnmarshalListOfMaps 在 Go 中创建空值
【发布时间】:2018-09-17 18:11:59
【问题描述】:

我从 json 文件中放入项目,我的代码可以输出扫描结果 json,但尝试使用内置进程将其解组为我的类型只会创建空值/零值。

预期:0,番茄,0.50

实际:0, , 0

item.json

{
    "id" : {"N" : "0"},
    "description" : {"S": "tomato"},
    "price" : {"N": "0.50"}
}

product.go

type product struct {
    id          int
    description string
    price       float64
}

我的查询功能:

func listAllProducts() []product {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-east-1"),
    },
    )
    svc := dynamodb.New(sess)
    productList := []product{}

    input := &dynamodb.ScanInput{
        TableName: aws.String("Products"),
    }
    result, err := svc.Scan(input)
    err = dynamodbattribute.UnmarshalListOfMaps(result.Items, &productList)
    return productList
}

输出代码

productList := listAllProducts()

    for _, p := range productList {
        log.Println(strconv.Itoa(p.id) + ", " + p.description + ", " + strconv.FormatFloat(p.price, 'f', -1, 64))
    }

【问题讨论】:

    标签: json amazon-web-services go amazon-dynamodb unmarshalling


    【解决方案1】:

    Marshal documentation 说:

    除非满足以下任一条件,否则所有结构字段和匿名字段都将被封送。

    • 该字段未导出

    Unmarshal 文档没有提及关于非导出字段的任何内容,但在 Go 中解编组也忽略非导出字段是常见且预期的(毕竟你甚至不能 set non-exported fields 使用 Go 的反射)。

    我不知道如何使用 DynamoDB,但如果您的字段被导出,您的运气可能会更好:

    type product struct {
        Id          int
        Description string
        Price       float64
    }
    

    如果您需要使用小写字段名称编组您的结构,可以使用dynamodbav 结构标签。

    我还建议注意dynamodbattribute.UnmarshalListOfMaps 返回的错误:

    err = dynamodbattribute.UnmarshalListOfMaps(result.Items, &productList)
    if err != nil {
        /* Do something with the error here even if you just log it. */
    }
    

    svc.Scan(input) 调用和其他所有返回错误的东西也是如此。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 2012-07-28
      • 2018-12-03
      • 2016-11-30
      • 2018-04-29
      • 2016-01-25
      • 1970-01-01
      相关资源
      最近更新 更多