简体   繁体   English

使用 Lambda 解析在 S3 中上传的 JSON 文件

[英]Parse JSON file uploaded in S3 using Lambda

I'm trying to parse a JSON file that get's uploaded in S3.我正在尝试解析在 S3 中上传的 JSON 文件。 I invoke the lambda function using an S3 PUT/POST method trigger.我使用 S3 PUT/POST 方法触发器调用 lambda function。

I'm using the following code.. however i'm not able to parse the json file.我正在使用以下代码..但是我无法解析 json 文件。 Can someone please help me?有人可以帮帮我吗?

var aws = require('aws-sdk');
var s3 = new aws.S3();


exports.handler = async (event, context, callback) => {

    var srcBucket = event.Records[0].s3.bucket.name;
    var srcKey = event.Records[0].s3.object.key;

    console.log("Params: srcBucket: " + srcBucket + " srcKey: " + srcKey + "\n");
    var getParams = {
        Bucket: srcBucket,
        Key: srcKey,
    };

    s3.getObject(getParams, function (err, data) {
        if (err) console.log(err, err.stack);
        else {
            console.log(JSON.stringify(data.Body.toString()));
        }
    });
};

Your code looks correct However, I'd suggest taking the example from AWS docs as your starting point.您的代码看起来正确但是,我建议您将AWS 文档中的示例作为您的起点。 Since your Lambda handler is an async handler, you have to await the promise returned by s3.getObject() , otherwise your function will complete before the callback executes (see the example code from the link).由于您的 Lambda 处理程序是async处理程序,因此您必须await s3.getObject()返回的 promise ,否则您的 function 将在回调执行之前完成(请参阅链接中的示例代码)

Since you mention that your Lambda function cannot parse the file, I assume the function gets invoked by S3 trigger (ie you can see the console.log('Params: ...) line in Cloudwatch Logs).由于您提到您的 Lambda function 无法解析文件,我假设 function 被 S3 触发器调用(即您可以在 Cloudwatch Logs 行中看到console.log('Params: ...) )。 If that's not the case, first check that the S3 trigger is configured correctly and S3 has permission to invoke the Lambda function.如果不是这种情况,首先检查 S3 触发器是否配置正确,并且 S3 有权调用 Lambda function。 If you created the function via AWS Console, this permission would have been set automatically.如果您通过 AWS 控制台创建了 function,则会自动设置此权限。

The next step I'd suggest is to check the Lambda function's IAM role.我建议的下一步是检查 Lambda 函数的 IAM 角色。 Check if the IAM role has s3:GetObject permission for your bucket and all objects under it or for the specific prefix you have configured S3 notification (eg <bucket>/* or <bucket>/prefix/* ).检查 IAM 角色是否对您的存储桶及其下的所有对象或您已配置 S3 通知的特定前缀(例如<bucket>/*<bucket>/prefix/* )具有s3:GetObject权限。

If the Lambda IAM permissions are correct, you'll have to check S3 bucket policies.如果 Lambda IAM 权限正确,您必须检查 S3 存储桶策略。 I suspect you haven't set up bucket policies according to what you describe.我怀疑您没有根据您的描述设置存储桶策略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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