I'm trying to acquire the most recent entry into DynamoDB or to parse out the results I get, so I can skim the most recent item off the top.
This is my code
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))
My results are a lot of the following that I'd like to either parse or if someone knows the code to just select the top entry that would be great.
{"MinorID": 123, "Location": "123westsideave"}
{"MinorID": 321, "Location": "456nowhererd"}
{"MinorID": 314, "Location": "123westsideave"}
KeySchema. Specifies the attributes that make up the primary key for a table or an index. The attributes in KeySchema must also be defined in the AttributeDefinitions array. For more information, see Data Model in the Amazon DynamoDB Developer Guide.
Optionally, you can provide a sort key attribute and use a comparison operator to refine the search results. Use the KeyConditionExpression parameter to provide a specific value for the partition key. The Query operation will return all of the items from the table or index with that partition key value.
at the end of my code where it says "print(json.dumps(i, cls=DecimalEncoder))" I changed that to "d = ast.literal_eval((json.dumps(i, cls=DecimalEncoder)))" I also added import ast at the top. It worked beautifully.
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With