简体   繁体   中英

How do I parse the data structure sent by DynamoDB to Lambda using python?

I am trying to link DynamoDB with Amazon Lambda such that when an item is inserted in DynamoDB, it will be sent to my lambda function which will parse the data structure and perfomr operations on the data. However, the data posted looks like this :

{
      "Records": [
        {
          "eventID": "ebefd45a0610c7a54654nb09b491c7c",
          "eventVersion": "1.1",
          "dynamodb": {
            "SequenceNumber": "3300000555554005534567541",
            "Keys": {
              "Id": {
                "S": "13"
              }
            },
            "SizeBytes": 100,
            "NewImage": {
              "url": {
                "S": "http:\/\/test.com\/blog\/tips-on-choosing-a-suitable-company-2\/"
              },
              "db_ref_id": {
                "S": "123"
              },
              "Id": {
                "S": "13"
              }
            },
            "ApproximateCreationDateTime": 1472638500,
            "StreamViewType": "NEW_AND_OLD_IMAGES"
          },
          "awsRegion": "us-west-2",
          "eventName": "INSERT",
          "eventSourceARN": "arn:aws:dynamodb:us-west-2:3454354:table\/urls\/stream\/2016-08-31T07:21:11.412",
          "eventSource": "aws:dynamodb"
        }
      ]
    }

I found this piece of code online that does this :

for record in event['Records']:
        print(record['eventID'])

However, I modified my code to this, and it doesn't work :

for record in event['Records']:
        print(record['dynamodb']['NewImage']['url']['S'])

Since I am not much aware of python, I'm not sure what is the best way of parsing this data structure. Any suggestions would really help.

print string['Records'][0]['eventID'] to print the eventID

There are many data structures involved here. The outer one being a python dictionary whose objects you can receive using keys. In our case you have only one mapping in your dictionary so, assuming that the whole data structure you have up there is assigned in variable named event you could do event['Records']. Later on, you have a list [] whose elements you can only fetch using indexes. (ex. list[1], list[2] etc)

Since from the format you have I suppose that you might have many records you could:

for record in event['Records']: print(record['dynamodb']['NewImage']['url']['S'])

This should print what you want, if the data posted on above is a string the parsing needs to take place using the json python module first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM