【发布时间】:2020-03-19 04:29:17
【问题描述】:
{ L:[{ N: "123"}, { N: "543"} ]}
有没有一种简单的方法来解组这样的 dynamodb 属性值
【问题讨论】:
标签: amazon-web-services go amazon-dynamodb
{ L:[{ N: "123"}, { N: "543"} ]}
有没有一种简单的方法来解组这样的 dynamodb 属性值
【问题讨论】:
标签: amazon-web-services go amazon-dynamodb
键 (L,N) 周围没有双引号,因此您无法使用 json.unmarshal 函数解组它们。您可以尝试以下方式来解组提到的 json 字符串。
package main
import (
"encoding/json"
"fmt"
"strings"
)
type Response struct {
L []InnerElement `json:"L"`
}
type InnerElement struct {
N string `json:"N"`
}
func main() {
st := `{L:[{ N: "123"},{ N: "543"}]}`
st = strings.Replace(st,"N",`"N"`,2)
st = strings.Replace(st,"L",`"L"`,1)
var res Response
err := json.Unmarshal([]byte(st), &res)
if err!=nil{
fmt.Print("error with json unmarshaling")
}
//print value
fmt.Println(res.L)
}
用双引号替换键。
【讨论】:
我假设您正在使用 aws-sdk-go 包,并且该输出来自扫描或查询结果。如果是这样,子包 dynamodbattribute 提供解组实用程序来将 dynamodb.AttributeValue 转换为您的结构:
// var result *dynamodb.ScanOutput
// This can be a list of struct too, but your sample output looks like a list of numbers.
nums := make([]int, 0, *result.Count)
if err := dynamodbattribute.UnmarshalListOfMaps(result.Items, &nums); err != nil {
// handle error
} else {
fmt.Println(nums)
}
【讨论】:
dynamodbattribute.UnmarshalMap 函数