Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting DynamoDB data to normal JSON in AWS Lambda

I'm using AWS Lambda to scan data from a DynamoDB table. This is what I get in return:

{   "videos": [     {       "file": {         "S": "file1.mp4"       },       "id": {         "S": "1"       },       "canvas": {         "S": "This is Canvas1"       }     },     {       "file": {         "S": "main.mp4"       },       "id": {         "S": "0"       },       "canvas": {         "S": "this is a canvas"       }     }   ] } 

My front-end application is using Ember Data Rest Adapter which does not accepts such response. Is there any way I can get normal JSON format? There is this NPM module called dynamodb-marshaler to convert DynamoDB data to normal JSON. I'm looking for a native solution if possible.

like image 281
Chaitanya Avatar asked Sep 22 '15 08:09

Chaitanya


1 Answers

Node.js Use the unmarshall function from AWSJavaScriptSDK:

const AWS = require("aws-sdk");      exports.handler = function( event, context, callback ) {     const newImages = event.Records.map(             (record) => AWS.DynamoDB.Converter.unmarshall(record.dynamodb.NewImage)     );     console.log('Converted records', newImages);     callback(null, `Success`); } 

Python Use TypeDeserializer.deserialize from boto3.dynamodb.types:

import json from boto3.dynamodb.types import TypeDeserializer  def ddb_deserialize(r, type_deserializer = TypeDeserializer()):     return type_deserializer.deserialize({"M": r})  def lambda_handler(event, context):     new_images = [ ddb_deserialize(r["dynamodb"]["NewImage"]) for r in event['Records'] ]     print('Converted records', json.dumps(new_images, indent=2)) 
like image 127
David Rissato Cruz Avatar answered Sep 28 '22 14:09

David Rissato Cruz