dynamodb-json - DynamoDB Json encoder#

DynamoDB JSON util to load and dump strings of Dynamodb JSON format to python object and vise-versa.

Overview#

DynamoDB JSON 是 Amazon DynamoDB 数据库的内部存储格式, 类似于 JSON. 不过它在此之上用 JSON 构建了一套类型系统 (这里有个 例子)

比如 Python 中的 {"name": "Alice"}, DynamoDB JSON 中就是 {"name": {"S": "Alice"}}. 这个 "S" 就是用来表示类型的.

dynamodb-json 这个库可以帮我们做到在普通 Python 字典和 DynamoDB JSON 之间的转换. 这个库的底层用了 boto3.dynamodb.types.TypeSerializer 这个能把 Python 对象转化成 DynamoDB 对象的类. 所以它依赖于 boto3. 我个人认为这种序列化工具应该尽量保持轻量, 没有依赖. 不过这个库的功能确实很实用, 所以我还是推荐使用.

还有一个库 pynamodb 也能做到这一点, 不过它需要先定义一个类, 比较的麻烦.

Example#

example.py
 1# -*- coding: utf-8 -*-
 2
 3from dynamodb_json import json_util
 4from rich import print as rprint
 5
 6py_data = {
 7    "id": 1,
 8    "name": "Alice",
 9    "age": 25,
10    "weight": 94.7,
11    "bio": {
12        "dob": "1990-01-01",
13        "address": "123 Main St.",
14        "hometown": None,
15    },
16    "relationships": [
17        {"name": "Bob", "relation": "friend"},
18        {"name": "Charlie", "relation": "father"},
19    ],
20}
21
22s = json_util.dumps(py_data)
23rprint(f"{type(s) = }")  # str
24print(s)
25"""
26{"id": {"N": "1"}, "name": {"S": "Alice"}, "age": {"N": "25"}, "weight": {"N": "94.7"}, "bio": {"M": {"dob": {"S": "1990-01-01"}, "address": {"S": "123 Main St."}, "hometown": {"NULL": true}}}, "relationships": {"L": [{"M": {"name": {"S": "Bob"}, "relation": {"S": "friend"}}}, {"M": {"name": {"S": "Charlie"}, "relation": {"S": "father"}}}]}}
27"""
28
29d = json_util.dumps(py_data, as_dict=True)
30rprint(f"{type(d) = }")  # dict
31rprint(d)  #
32"""
33{
34    'id': {'N': '1'},
35    'name': {'S': 'Alice'},
36    'age': {'N': '25'},
37    'weight': {'N': '94.7'},
38    'bio': {
39        'M': {
40            'dob': {'S': '1990-01-01'},
41            'address': {'S': '123 Main St.'},
42            'hometown': {'NULL': True}
43        }
44    },
45    'relationships': {
46        'L': [
47            {'M': {'name': {'S': 'Bob'}, 'relation': {'S': 'friend'}}},
48            {'M': {'name': {'S': 'Charlie'}, 'relation': {'S': 'father'}}}
49        ]
50    }
51}
52"""
53
54res = json_util.loads(s)
55rprint(f"{type(res) = }")  # dict
56rprint(res)  # dict
57"""
58{
59    'id': 1,
60    'name': 'Alice',
61    'age': 25,
62    'weight': 94.7,
63    'bio': {'dob': '1990-01-01', 'address': '123 Main St.', 'hometown': None},
64    'relationships': [
65        {'name': 'Bob', 'relation': 'friend'},
66        {'name': 'Charlie', 'relation': 'father'}
67    ]
68}
69"""
70
71res = json_util.loads(d)
72rprint(f"{type(res) = }")  # dict
73rprint(res)  # dict
74"""
75{
76    'id': 1,
77    'name': 'Alice',
78    'age': 25,
79    'weight': 94.7,
80    'bio': {'dob': '1990-01-01', 'address': '123 Main St.', 'hometown': None},
81    'relationships': [
82        {'name': 'Bob', 'relation': 'friend'},
83        {'name': 'Charlie', 'relation': 'father'}
84    ]
85}
86"""