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
}