DynamoDB UnmarshalListOfMaps在Go中创建空值

1 json go unmarshalling amazon-web-services amazon-dynamodb

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

预期:0,番茄,0.50

实际:0,,0

item.json

{
    "id" : {"N" : "0"},
    "description" : {"S": "tomato"},
    "price" : {"N": "0.50"}
}
Run Code Online (Sandbox Code Playgroud)

product.go

type product struct {
    id          int
    description string
    price       float64
}
Run Code Online (Sandbox Code Playgroud)

我的查询功能:

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
}
Run Code Online (Sandbox Code Playgroud)

输出代码

productList := listAllProducts()

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

mu *_*ort 5

Marshal文件说:

除非满足以下任何条件,否则将封送所有结构字段以及带有匿名字段的字段。

  • 该字段未导出

Unmarshal文档没有提及任何有关非导出字段的内容,但是在Go中常见的做法是期望它能够编组也忽略非导出字段(毕竟,您甚至无法使用Go的反射来设置非导出字段)。

我不了解DynamoDB的处理方式,但是如果导出了字段,也许运气更好:

type product struct {
    Id          int
    Description string
    Price       float64
}
Run Code Online (Sandbox Code Playgroud)

还有dynamodbav,如果你需要用小写字段名元帅你的结构提供结构的标签。

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

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

对于svc.Scan(input)调用以及返回错误的所有其他操作类似。