PythonのDict型をDynamoDB形式のJsonに変換する
pythonでDynamoDB関連操作をするとき、難しい点の一つは一つは以下のようなDynamoDBの独特なJSON形式だと思います。
Python用のAWS SDKであるBoto3にはDynamoDB形式のJsonをPythonのDictに変換できるTypeSerializerとTypeDeserializerがあります。
https://boto3.amazonaws.com/v1/documentation/api/latest/_modules/boto3/dynamodb/types.html
{
"id": {
"N": 12345
},
"name": {
"S": "TanakaTaro"
}
}
Python用のAWS SDKであるBoto3にはDynamoDB形式のJsonをPythonのDictに変換できるTypeSerializerとTypeDeserializerがあります。
https://boto3.amazonaws.com/v1/documentation/api/latest/_modules/boto3/dynamodb/types.html
TypeSerializer
PythonのDictをDynamoDB形式のJsonに変換します。個人的には変換結果で最初の{"M": ...}はなくしてほしいですが…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from boto3.dynamodb.types import TypeSerializer | |
some_item = { | |
"id" : 12345, | |
"name" : "TanakaTaro", | |
"Map" : {"map_id" : 54321}, | |
"List" : ["A", "B", "C"] | |
} | |
type_serializer = TypeSerializer() | |
result = type_serializer.serialize(some_item) | |
print(result) | |
# Result | |
# {'M': | |
# { | |
# 'id': {'N': '12345'}, | |
# 'name': {'S': 'TanakaTaro'}, | |
# 'Map': { | |
# 'M': { | |
# 'map_id': {'N': '54321'} | |
# } | |
# }, | |
# 'List': { | |
# 'L': [{'S': 'A'}, {'S': 'B'}, {'S': 'C'}] | |
# } | |
# } | |
# } |
TypeDeserializer
DynamoDB形式のJsonをPythonのDictに変換します。こちらも一気に変換はできず、各Keyごとに変換が必要です。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from boto3.dynamodb.types import TypeDeserializer | |
import pprint,json | |
type_deserializer = TypeDeserializer() | |
pp = pprint.PrettyPrinter() | |
some_item_json = '{"id": {"N": "12345"}, "name": {"S": "TanakaTaro"}, "Map": {"M": {"map_id": {"N": "54321"}}}, "List": {"L": [{"S": "A"}, {"S": "B"}, {"S": "C"}]}}' | |
# String to Json | |
some_item = json.loads(some_item_json) | |
result = {} | |
for key in some_item: | |
result[key] = type_deserializer.deserialize(some_item[key]) | |
pp.pprint(result) | |
# Result | |
# { | |
# 'List': ['A', 'B', 'C'], | |
# 'Map': {'map_id': Decimal('54321')}, | |
# 'id': Decimal('12345'), | |
# 'name': 'TanakaTaro'} |
まとめ&蛇足
- TypeSerializerとTypeDeserializerはDynamoDBのデータをpythonで処理したいときや処理後にまたDynamoDBにアップロードしたいときに有効に利用できそうです。
- ただ、そのまま利用するよりは、利用しやすくカスタム関数やクラスを作成したほうがよさそうです。
- JavaScriptのSDKにもConverterというものがあるようです