Search code examples
pythonamazon-dynamodbboto3

How to map/serialize data in dynamodb via python?


Based on aws documentation , https://docs.aws.amazon.com/code-library/latest/ug/python_3_dynamodb_code_examples.html, i'm using boto3 client to create/update data in a dynamodb table. dynamodb supports string, numbers , lists ,sets and boolean (see sample below) . based on the example, i'm setting an item , with a boolean . but i get an error that expected value for attribute is string, but i'm trying to set it as a boolean true/false value. how do i construct my request , such that i can set a boolean value in dynamo db via python? I understand the item is a python dictonary, i can set string values but not boolean?

db = boto3.client('dynamo')
        try:
            db.put_item(
                Item={
                    "year": year,
                    "title": title,
                    "info": {"plot": plot, "rating": Decimal(str(rating))},
                     "rating" : 42,
                     "award" : {"BOOL": False}
                }
            )
        except ClientError as err:
            logger.error(err)

Solution

  • In your code, you are using a mixture of data types with the low level client, which supports DynamoDB-JSON only.

    Have a read of this blog post: https://aws.amazon.com/blogs/database/exploring-amazon-dynamodb-sdk-clients/

    Using low level client would be:

    {'mybool': {'BOOL': False}}

    dynamo = boto3.client('dynamodb') #dynamodb not dynamo
    try:
           dynamo.put_item(
            TableName='MyTable',
            Item={
                "dob": {"N": "1985"},
                "name": {"S": title},
                "info": {
                    "M": {
                        "email": {"S": "abc@xyz.com"},
                        "phone": {"S": "12093849393"}
                    }
                },
                "paid": {"BOOL": False}
            }
        )
    except ClientError as err:
         logger.error(err)
    

    High level client:

    'mybool' : False

    dynamo = boto3.client('dynamodb') #dynamodb not dynamo
    table = dynamo.Table('MyTable')
    try:
        dynamo.put_item(
         Item={
          "dob": 1985,
          "name": "title",
          "info": {
               "email": "abc@xyz.com",
               "phone": "12093849393"
           },
            "paid": False
         }
        )
    except ClientError as err:
         logger.error(err)