由于客户函数错误,Lambda 执行失败,状态为 200:“Decimal”类型的对象不可 JSON 序列化
我在以下链接中浏览了所有现有的解决方案,但没有任何对我有用。我究竟做错了什么?:Python JSON 序列化 Decimal 对象
import json
import boto3
import decimal
client = boto3.resource('dynamodb')
table = client.Table('table')
def lambda_handler(event, context):
method = event["httpMethod"]
print(event)
if method=="POST":
return POST(event)
elif method=="DELETE":
return DELETE(event)
elif method=="GET":
return GET(event)
#the respons format
def send_respons(responseBody, statusCode):
response = {
"statusCode": statusCode,
"headers": {
"my_header": "my_value"
},
"body": json.dumps(responseBody),
"isBase64Encoded": 'false'
}
return response
def GET(event):
tab = table.scan()['Items']
ids = []
for item in tab:
ids.append({"id":item["id"], "decimalOBJ":decimal.Decimal(item["decimalOBJ"]}))
return send_respons(ids, 201)
这是一个扩展的例子JSONEncoder
处理Decimal
类型也指定在json 文档
from decimal import Decimal
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return str(obj)
return json.JSONEncoder.default(self, obj)
使用调用它
json.dumps(some_object, cls=DecimalEncoder)
通过转换为str
无需依赖外部封装即可保持良好的精度。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)