简体   繁体   中英

Reading XML from S3 Python AWS Lambda

I am trying to read a file in an s3 bucket and extract elements with xml minidom in a python AWS Lambda function. I keep getting error - "errorMessage": "Unable to marshal response: Object of type Element is not JSON serializable".

import json
from xml.dom import minidom
import boto3

s3 = boto3.resource('s3')

def lambda_handler(event, context):
   bucketname = 'mybucket' 
   filename = 'myfile.xml' 
   obj = s3.Object(bucketname, filename)
   file_data = obj.get()['Body'].read()

   #parse xml
   xmldoc = minidom.parseString(file_data)
   message_1 = xmldoc.getElementsByTagName('id')

   #return
   return {
      "bucketname": bucketname,
      "file_data": file_data,
      "id": message_1
   }

getElementsByTagName returns a NodeList which contains Elements which in turn aren't JSON serializable. If you expect there to only ever be 1 id element in your xml, you can do

   return {
      "bucketname": bucketname,
      "file_data": file_data,
      "id": message_1.item(0).firstChild.data
   }

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