简体   繁体   English

将 AWS DynamoDB 数据转换为 Python/Boto3/Lamba 中的 json 格式

[英]AWS DynamoDB data to json format in Python/Boto3/Lamba

I have a DynamoDB table, which needs to be converted to json format and shared across API response using Python/Boto3/AWS-Lambda environment.我有一个 DynamoDB 表,需要将其转换为 json 格式并使用 Python/Boto3/AWS-Lambda 环境在 API 响应之间共享。

userMetrics[
{
  "userid": 1234567890,  ==> key
  "likemetrics": 0,
  "lasttimestamp": 1604553995
},
{
  "userid": 1234567891,  ==> key
  "likemetrics": 0,
  "lasttimestamp": 1604553998
}]

I am trying to copy the entire DynamoDB table to json format using the examples mentioned in Formatting DynamoDB data to normal JSON in AWS Lambda but face error on execution as我正在尝试使用将DynamoDB 数据格式化为 AWS Lambda 中的普通 JSON 中提到的示例将整个 DynamoDB 表复制为 json 格式,但在执行时遇到错误

{
"errorMessage": "'dynamodb.Table' object has no attribute 'items'",
"errorType": "AttributeError",
"stackTrace":[
"  File \"/var/task/lambda_function.py\", line 75, in lambda_handler\n    'usermetrics': json.dumps(from_dynamodb_to_json(dydb_userTable))\n",
"  File \"/var/task/lambda_function.py\", line 7, in from_dynamodb_to_json\n    return {k: d.deserialize(value=v) for k, v in item.items()}\n"
]
}

My lambda code implementation:我的 lambda 代码实现:

import json
import boto3
from boto3.dynamodb.types import TypeDeserializer, TypeSerializer

def from_dynamodb_to_json(item):
    d = TypeDeserializer()
    return {k: d.deserialize(value=v) for k, v in item.items()}

dydb = boto3.resource('dynamodb')
dydb_userTable = dydb.Table('userMetrics')

def lambda_handler(event, context):
        return {
            'statusCode': 200,
            'usermetrics': json.dumps(from_dynamodb_to_json(dydb_userTable))
        }

The Table ( dydb_userTable in your code) object does not have the items that you're looking for. Table (代码中的dydb_userTable )对象没有您要查找的items You need to call a method on that table that will retrieve the items for you such as dydb_userTable.scan() or dydb_userTable.query() .您需要在该表上调用一个方法,该方法将为您检索项目,例如dydb_userTable.scan()dydb_userTable.query()

Reference: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#table参考: https : //boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM