在 python 中使用 Boto3 从 dynamodb 中获取结果并解析为可用的变量或字典

Using Boto3 in python to acquire results from dynamodb and parse into a usable variable or dictionary

我正在尝试获取 DynamoDB 的最新条目或解析我得到的结果,以便我可以从顶部浏览最近的项目。

这是我的代码

from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource('dynamodb', region_name='us-west-2',
endpoint_url="https://foo.foo.foo/aws")

table = dynamodb.Table('footable')
response = table.scan(
    Select="ALL_ATTRIBUTES",
    )

for i in response['Items']:
    print(json.dumps(i, cls=DecimalEncoder))

我的结果有很多,我想对其进行解析,或者如果有人知道代码只是 select 最上面的条目,那就太好了。

{"MinorID": 123, "Location": "123westsideave"}
{"MinorID": 321, "Location": "456nowhererd"}
{"MinorID": 314, "Location": "123westsideave"}

在我的代码末尾显示 "print(json.dumps(i, cls=DecimalEncoder))" 我将其更改为 "d = ast.literal_eval((json.dumps(i, cls=DecimalEncoder)))" 我还在顶部添加了 import ast。效果很好。

import ast

table = dynamodb.Table('footable')
response = table.scan(
    Select="ALL_ATTRIBUTES",
    )

for i in response['Items']:
    d = ast.literal_eval((json.dumps(i, cls=DecimalEncoder)))
import boto3
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return str(o)
        if isinstance(o, set):  #<---resolving sets as lists
            return list(o)
        return super(DecimalEncoder, self).default(o)


dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('mytable')

response = table.query(
    KeyConditionExpression=Key('object_type').eq("employee")
)

print(json.dumps((response), indent=4, cls=DecimalEncoder))