【问题标题】:Is there easier way to unmarshall dynamodb attribute value有没有更简单的方法来解组 dynamodb 属性值
【发布时间】:2020-03-19 04:29:17
【问题描述】:

{ L:[{ N: "123"}, { N: "543"} ]}

有没有一种简单的方法来解组这样的 dynamodb 属性值

【问题讨论】:

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


    【解决方案1】:

    键 (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)
    
    
    }
    

    用双引号替换键。

    【讨论】:

      【解决方案2】:

      我假设您正在使用 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)
      }
      

      【讨论】:

      • 您认为 UnmarshalList 是否适用于 DynamoDB 的 GetItem 函数/方法?
      • 不,它不适用于 GetItem。您可能需要检查 dynamodbattribute.UnmarshalMap 函数
      猜你喜欢
      • 1970-01-01
      • 2011-10-26
      • 2021-11-08
      • 1970-01-01
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多