如何将DynamoDB的LastEvaluatedKey序列化为字符串?

huangapple go评论82阅读模式
英文:

How to serialize DynamoDB LastEvaluatedKey to string

问题

有一个要求,需要将查询输出中返回的LastEvaluatedKey作为分页API调用的响应进行转换,以便用户可以使用LastEvaluatedKey请求下一页。是否可以使用aws-sdk-go-v2进行转换?

尝试使用json进行编组和解组,但未成功。

lek := map[string]types.AttributeValue{
    "num":  &types.AttributeValueMemberN{Value: "1"},
    "text": &types.AttributeValueMemberS{Value: "text"},
}
barray, err := json.Marshal(lek)
if err != nil {
  fmt.Println(err)
}

lekDecoded := map[string]types.AttributeValue{}
err = json.Unmarshal(barray, &lekDecoded)
if err != nil {
 fmt.Println(err)
}

这始终无法将其解码回map[string]types.AttributeValue。

英文:

Have a requirement of transferring the LastEvaluatedKey returned from the query output as the response of a paginated API call so that the users can request the next page with the LastEvaluatedKey.
Is it possible to convert with aws-sdk-go-v2 ?

Have tried to marshal and unmarshal using json but it was not working

lek := map[string]types.AttributeValue{
    "num":  &types.AttributeValueMemberN{Value: "1"},
    "text": &types.AttributeValueMemberS{Value: "text"},
}
barray, err := json.Marshal(lek)
if err != nil {
  fmt.println(err)
}

lekDecoded := map[string]types.AttributeValue{}
err = json.Unmarshal(barray, &lekDecoded)
if err != nil {
 fmt.println(err)
}

This always keeps failing to decode it back to map[string]types.AttributeValue

答案1

得分: 2

LastEvaluatedKey在响应中以纯文本形式提供。如果你想对其进行编码,可以使用base64等方式进行编码。你可以选择任何类型的编码,只要在提供给下一个分页请求之前进行解码即可。

编码LEK

aws dynamodb scan \
--table-name test \
--limit 1 \
--query LastEvaluatedKey | base64
ewogICAgImlkIjogewogICAgICAgICJTIjogIjR3OG5pWnBpTXk2cXoxbW50RkE1dSIKICAgIH0KfQo

解码编码后的LEK

echo ewogICAgImlkIjogewogICAgICAgICJTIjogIjR3OG5pWnBpTXk2cXoxbW50RkE1dSIKICAgIH0KfQo | base64 --decode
{
    "id": {
        "S": "4w8niZpiMy6qz1mntFA5u"
    }
}
英文:

LastEvaluatedKey is provided in plain text in the response. If you want to encode it, you can do so using base64 for example. You can choose any type of encoding so long as you decode before supplying back to the next paged request.

Encode LEK

aws dynamodb scan \
--table-name test \
--limit 1 \
--query LastEvaluatedKey | base64
ewogICAgImlkIjogewogICAgICAgICJTIjogIjR3OG5pWnBpTXk2cXoxbW50RkE1dSIKICAgIH0KfQo

Decode encoded LEK

echo ewogICAgImlkIjogewogICAgICAgICJTIjogIjR3OG5pWnBpTXk2cXoxbW50RkE1dSIKICAgIH0KfQo | base64 --decode
{
    "id": {
        "S": "4w8niZpiMy6qz1mntFA5u"
    }
}

huangapple
  • 本文由 发表于 2023年1月17日 04:05:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75139176.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定