- 最新
- 投票最多
- 评论最多
Decimal object is not JSON serializable. Use a package that can do that for you [1] or consider casting the Decimal into a float using a helper function [2].
-
Use
simplejson
instead ofjson
as it will do the decimal conversion for you. This would mean you need to use a Lambda layer to import that pip package.import simplejson as json
-
Use a custom class to do the conversion meaning you can avoid the Lambda layer:
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(item, cls=DecimalEncoder)
When you say "one table doesn't work" could you provide more information? Such as an error message? Or what you're expecting.
As I understand it, table.scan()
only scans a single table so I'm not sure what is meant by "it applied 3 tables".
Running json.dumps(table.scan()['Items'])
will return all of the items in the table. Running json.dumps(table.scan()['Items'][0])
will return the first element of the list.
My code is
def lambda_handler(event, context): dynamodb = boto3.resource("dynamodb") table = dynamodb.Table("OrderList") items = table.scan()['Items'] return { 'statusCode': 200, 'body': json.dumps(items[1]) }
Response is { "statusCode": 200, "body": "{"TotalPrice": "101", "PartName": "Test Part", "ClientID": "user001", "UnitPrice": "50", "OrderDate": "28-10-2022", "PartID": "P003", "Status": "Sent", "Quantity": "1", "OrderID": "O0001"}" }
################################### return { 'statusCode': 200, 'body': json.dumps(items[1]) }
Response is { "errorMessage": "Object of type Decimal is not JSON serializable", "errorType": "TypeError", "requestId": "5849b770-4dc6-4858-82ed-65fbecab1f6a", "stackTrace": [ " File "/var/task/lambda_function.py", line 76, in lambda_handler\n 'body': json.dumps(items)\n", " File "/var/lang/lib/python3.9/json/init.py", line 231, in dumps\n return _default_encoder.encode(obj)\n", " File "/var/lang/lib/python3.9/json/encoder.py", line 199, in encode\n chunks = self.iterencode(o, _one_shot=True)\n", " File "/var/lang/lib/python3.9/json/encoder.py", line 257, in iterencode\n return _iterencode(o, 0)\n", " File "/var/lang/lib/python3.9/json/encoder.py", line 179, in default\n raise TypeError(f'Object of type {o.class.name} '\n" ] }
相关内容
- AWS 官方已更新 1 年前
- AWS 官方已更新 5 个月前
- AWS 官方已更新 2 年前
- AWS 官方已更新 1 年前