Formatting DynamoDB data to normal JSON in AWS Lambda

前端 未结 8 1439
無奈伤痛
無奈伤痛 2020-12-01 02:55

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

{
  \"videos\": [
    {
      \"fil         


        
8条回答
  •  悲&欢浪女
    2020-12-01 03:17

    I think it's just a custom transformation exercise for each app. A simple conversion from DynamoDB's item format to you application format might look like this:

    var response = {...} // your response from DynamoDB
    var formattedObjects = response.videos.map(function(video) {
        return {
            "file": video.file.S,
            "id": video.id.S,
            "canvas": video.canvas.S
        };
    });
    

    If you want to build a generic system for this, you would have to handle DynamoDB's various AttributeValue types. A function like the one below would do the job, but I've left out the hard work of handling most of DynamoDB's more complex attribute value types:

    function dynamoItemToPlainObj(dynamoItem) {
        var plainObj = {};
        for (var attributeName in dynamoItem) {
            var attribute = dynamoItem[attributeName];
            var attributeValue;
            for (var itemType in attribute) {
                switch (itemType) {
                case "S":
                    attributeValue = attribute.S.toString();
                    break;
                case "N":
                    attributeValue = Number(attribute.N);
                    break;
                    // more attribute types...
                default:
                    attributeValue = attribute[itemType].toString();
                    break;
                }
            }
            plainObj[attributeName] = attributeValue;
        }
        return plainObj;
    }    
    var formattedObjects = response.videos.map(dynamoItemToPlainObj);
    

提交回复
热议问题