LoginSignup
10
2

More than 5 years have passed since last update.

Boto3を使ったら空文字のままだとDynamoDBにデータが入れられなかった話

Posted at

DynamoDBから怒られる

Boto3を使ってDynamoDBにデータを入れようとしました。
下記のようなものです。

{
    'accountId': '12345',
    'date': '2017-09-20',
    'list': ['aaa', 'a', ''],
    'name': 'aaa'
}

結果、

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the PutItem operation: One or more parameter values were invalid: An AttributeValue may not contain an empty string

怒られました。

そこで

下記のような関数をつくりました。辞書オブジェクト(登録するJSON)を引数で与えて、空文字をNoneで上書きます。

def emptystr_to_none(item):
    for k, v in item.items():
        if isinstance(v, dict):
            TrustedAdvisorCheck.json_parse(v)
        elif isinstance(v, list):
            for i in range(len(v)):
                list_elem = v[i]

                if isinstance(list_elem, str):
                    if list_elem == '':
                        v[i] = None
                elif isinstance(list_elem, list) or isinstance(list_elem, dict):
                    TrustedAdvisorCheck.json_parse(list_elem)
        elif isinstance(v, str):
            if v == '':
                item[k] = None

    return item

結果

下記のように変換して、登録できました。

{
    'accountId': '12345',
    'date': '2017-09-20',
    'list': ['aaa', 'a', None],
    'name': 'aaa'
}
10
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
2