检索JSON元素nodejs lambda aws

时间:2018-10-01 05:46:24

标签: aws-lambda

我有一个lambda函数,它从dynamodb中检索元素。当我尝试从包含数据库中未定义元素的JSON对象中提取单个或多个Item时,如何返回单个元素?例如“ date_booking”。以下是该功能的代码。 预先感谢。

'use strict';

 const AWS = require('aws-sdk');
 const docClient = new AWS.DynamoDB.DocumentClient({region: 'us-west-2'});

 function close(sessionAttributes, fulfillmentState, message) {
       return {
               sessionAttributes,
        dialogAction: {
        type: 'Close',
        fulfillmentState,
        message,
                     },
                };
        }

// --------------- Events -----------------------


function dispatch(intentRequest, callback) {
    const sessionAttributes = intentRequest.sessionAttributes;
    const slots = intentRequest.currentIntent.slots;
    const phone = slots.PhoneNumber;

let params = {
    TableName: 'bookings',
    Key: {
        "phone_number": phone
    },
    ProjectionExpression:"date_booking, time_booking"
};

docClient.get(params, function(err, data) {
if (err) {
    callback(err, null);
} else {
    callback(null,data);

   console.log(data);
   console.log(data.date_booking);
   console.log(data.time_booking);

}
});    

}
// --------------- Main handler -----------------------

exports.handler = (event, context, callback) => {
try {
    dispatch(event,
        (response) => {
            callback(null, response);
        });
} catch (err) {
    callback(err);
}
};

执行结果为:

Function Logs:
START RequestId: 5536b82c-c538-11e8-ad44-474e44b2f858 Version: $LATEST
2018-10-01T05:10:38.653Z    5536b82c-c538-11e8-ad44-474e44b2f858    { Item: 
{ date_booking: '2018-09-18', time_booking: '15:00' } }
2018-10-01T05:10:38.712Z    5536b82c-c538-11e8-ad44-474e44b2f858     
undefined
2018-10-01T05:10:38.730Z    5536b82c-c538-11e8-ad44-474e44b2f858     
undefined
END RequestId: 5536b82c-c538-11e8-ad44-474e44b2f858
REPORT RequestId: 5536b82c-c538-11e8-ad44-474e44b2f858  Duration: 1301.50 ms     
Billed Duration: 1400 ms    Memory Size: 128 MB Max Memory Used: 30 MB  

2 个答案:

答案 0 :(得分:0)

您可以使用以下内容。

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: 'us-west-2'});

exports.handler = (event, context, callback) => {
    var params = {
        TableName: 'bookings',
    Key:{
        date_booking: event.params.path.date_booking
        //date_booking is the item you want to retrieve
        }
    };

    docClient.get(params, function(err, data) {
    if (err) {
        callback(err, null);
        console.log(err)
    } else {
        callback(null, data);
        console.log(data);
      }
    });

};

答案 1 :(得分:0)

dynamoDB一样,从Item获取数据。

docClient.get(params, function(err, data) {
    if (err) {
        callback(err, null);
        console.log(err)
    } else {
        console.log(data.Item.date_booking);
      }
    });