From e9db7fe026ccc5c1dff179accee1d6b49c34bb9e Mon Sep 17 00:00:00 2001 From: Mohab Usama Date: Wed, 8 Mar 2017 19:22:17 +0100 Subject: [PATCH] Support Decimal values in JSONEncoder (#413) --- connexion/decorators/produces.py | 5 +++++ tests/test_produces.py | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/connexion/decorators/produces.py b/connexion/decorators/produces.py index b71ed4d76..8b4c46169 100644 --- a/connexion/decorators/produces.py +++ b/connexion/decorators/produces.py @@ -3,6 +3,8 @@ import functools import logging +from decimal import Decimal + import flask import six from flask import json @@ -30,6 +32,9 @@ def default(self, o): if isinstance(o, datetime.date): return o.isoformat() + if isinstance(o, Decimal): + return float(o) + return json.JSONEncoder.default(self, o) diff --git a/tests/test_produces.py b/tests/test_produces.py index 024c515f6..a90cd312a 100644 --- a/tests/test_produces.py +++ b/tests/test_produces.py @@ -1,5 +1,8 @@ import datetime import json +import math + +from decimal import Decimal from connexion.decorators.produces import JSONEncoder @@ -14,6 +17,12 @@ def test_json_encoder(): s = json.dumps(datetime.datetime.utcnow(), cls=JSONEncoder) assert s.endswith('Z"') + s = json.dumps(Decimal(1.01), cls=JSONEncoder) + assert s == '1.01' + + s = json.dumps(math.expm1(1e-10), cls=JSONEncoder) + assert s == '1.00000000005e-10' + def test_json_encoder_datetime_with_timezone():