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

Cfo*_*te7 5 python json boto amazon-web-services amazon-dynamodb

我曾经是MySQL和SQL Server的SQL查询大师,但我距离掌握nosql和dynamo db似乎还远远不够简化。无论如何,我都只是想获取dynamo db的最新条目,或者解析我得到的结果,以便可以从顶部浏览最新的条目。

这是我的代码

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))
Run Code Online (Sandbox Code Playgroud)

我的分析结果很多,我想分析一下,或者如果有人知道仅选择顶部条目的代码,那将会很棒。

{"MinorID": 123, "Location": "123westsideave"}
{"MinorID": 321, "Location": "456nowhererd"}
{"MinorID": 314, "Location": "123westsideave"}
Run Code Online (Sandbox Code Playgroud)

Cfo*_*te7 6

在我的代码末尾,它写着“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)))
Run Code Online (Sandbox Code Playgroud)


Ing*_*nga 5

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))
Run Code Online (Sandbox Code Playgroud)