简体   繁体   中英

Convert json to csv from one S3 bucket and upload to another S3 bucket through AWS Lambda

I have tried below code but I am not able to convert the data from json to csv. Can someone please help me?

import boto3
import botocore
import csv
def lambda_handler(event, context):
    BUCKET_NAME = 'name of the bucket' # replace with your bucket name
    KEY = 'OUTPUT.csv' # replace with your object key
    json_data = [{"id":"1","name":"test"},{"id":"2","name":"good"}]
    with open("data.csv", "w") as file:
        csv_file = csv.writer(file)
        csv_file.writerow(['id', 'name'])
        for item in data:
            csv_file.writerow([item.get('id'),item.get('name')])

    csv_binary = open('data.csv', 'rb').read()
    try:
        obj = s3.Object(BUCKET_NAME, KEY)
        obj.put(Body=csv_binary)
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == "404":
            print("The object does not exist.")
        else:
            raise
    s3client = boto3.client('s3')
    try:
        download_url = s3client.generate_presigned_url(
                         'get_object',
                          Params={
                              'Bucket': BUCKET_NAME,
                              'Key': KEY
                              },
                          ExpiresIn=3600
        )
        return {"csv_link": download_url}
    except Exception as e:
        raise utils_exception.ErrorResponse(400, e, Log)

Here is the response I am getting for the above code:

{
  "errorMessage": "[Errno 30] Read-only file system: 'data.csv'",
  "errorType": "OSError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 8, in lambda_handler\n    with open(\"data.csv\", \"wb\") as file:\n"
  ]
}

In AWS Lambda, you can only create files in the /tmp/ directory. Therefore, use:

with open("/tmp/data.csv", "w") as file:

A maximum of 512MB is provided, so it is a good idea to delete any temporary files so they do not interfere with future executions of the Lambda function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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