You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS Lambda函数中获取并打印S3上传的JSON文件内容?

在Lambda函数中获取并打印Amazon S3上传的JSON文件内容

你需要修改代码,从S3的getObject响应中提取Body字段,将其转换为字符串后解析成JSON对象,就能打印文件内容了。以下是修改后的完整代码:

// console.log('Loading function');
        
const aws = require('aws-sdk');

const s3 = new aws.S3({ apiVersion: '2006-03-01' });
    
exports.handler = async (event, context) => {
    // console.log('Received event:', JSON.stringify(event, null, 2));

    // 获取事件中的S3存储桶和对象键
    const bucket = event.Records[0].s3.bucket.name;
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    
    const params = {
        Bucket: bucket,
        Key: key,
    };
    
    try {
        // 获取S3对象的完整响应,包括Body和ContentType
        const { ContentType, Body } = await s3.getObject(params).promise();
        console.log('CONTENT TYPE:', ContentType);
        
        // 将Buffer类型的Body转换为字符串,再解析为JSON对象
        const jsonContent = JSON.parse(Body.toString());
        console.log('JSON文件内容:', jsonContent);
        
        return ContentType;
    } catch (err) {
        console.log(err);
        const message = `Error getting object ${key} from bucket ${bucket}. Error: ${err}`;
        console.log(message);
        throw new Error(message);
    }
};

关键修改说明:

  • 从getObject响应中同时解构出Body和ContentType,而不是只取ContentType
  • Body是Buffer类型,需要用toString()转换为字符串
  • 用JSON.parse()将字符串解析为JSON对象,之后就能直接打印或处理内容
  • 如果上传的文件可能不是合法JSON,建议在解析时增加额外的错误捕获,避免函数报错

注意事项:

  • 确保Lambda执行角色拥有S3的s3:GetObject权限,否则会出现权限错误
  • 如果JSON文件过大,要注意Lambda的内存和执行时间限制,必要时考虑分段读取

内容的提问来源于stack exchange,提问作者terry_alex_97

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 11:56:45