Extract information from SNS message

Viewed 1471

I am using the service AWS Textract to get a text from an image. The process steps are:

  1. Upload file to S3 and entry into Dynamodb
  2. Dynamodb triggers a lambda function for Textract and sends a message to SNS
  3. SNS triggers a lambda to write the extracted text into a Dynamodb table

My current problem is in step 3 reading the SNS message. The message looks like:

Lambda:

exports.handler = (event)  => {
    const message = event.Records[0].Sns.Message;
    console.log(message)
}

The output looks like:

  {
  Type: 'Notification',
  MessageId: '00cc3304-a54c-56e4-95c5-746b1579b7a3',
  TopicArn: 'arn:aws:sns:eu-west-1:878512516355:PDF_textprocessing_complete',
  Subject: null,
  Message: '{"JobId":"8ae4a56561be6ddc4e2c8365976f79c","Status":"SUCCEEDED","API":"StartDocumentTextDetection","Timestamp":1593159156962,"DocumentLocation":{"S3ObjectName":"private/eu-west-1:465233397-b3b0-4635-bd4d-249df960b2d6/276bff07-be35-4bf7-bc30-249e86adc3f38invoice_2020_march.png","S3Bucket":"doc9ce275171f09423c586885-dev"}}',
  Timestamp: '2020-06-54T08:18:37.012Z',
  SignatureVersion: '1',
  Signature: 'DdSXJfZvAnsWKnWd+Z7OaeM5MvfcvdzGBP==',
  SigningCertUrl: 'https://sns.eu-west-5.amazonaws.com/SimpleNotificationService-a863b10b4e1f29c941702d737128f7b6.pem',
  UnsubscribeUrl: 'https://sns.eu-west-5.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:eu-west-5:878519355:PDF_textprocessing_complete:ec5c7a10-2ca-47f7-b1ac-0d0e5fd895618b',
  MessageAttributes: {}
}

How can I extract JobId and S3ObjectName into a variable?

Many thanks in advance!!

1 Answers

You would use the JSON.parse function to access the properties of the Message property such as below.

exports.handler = (event)  => {
    const message = event.Records[0].Sns.Message;
    console.log(message);
    const jobid = JSON.parse(message).JobId
    const object = JSON.parse(message).DocumentLocation.S3ObjectName
}
Related