我正在使用django-restframework
,并且我正在使用JSONRenderer
来呈现我的返回响应。
但我总是得到这样的错误:
response = response.render()
File "C:\Users\Domob\Desktop\dev\venv_bv_crm\lib\site-packages\django\template\response.py", line 106, in render
self.content = self.rendered_content
File "C:\Users\Domob\Desktop\dev\venv_bv_crm\lib\site-packages\rest_framework\response.py", line 70, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "C:\Users\Domob\Desktop\dev\venv_bv_crm\lib\site-packages\rest_framework\renderers.py", line 104, in render
allow_nan=not self.strict, separators=separators
File "C:\Users\Domob\Desktop\dev\venv_bv_crm\lib\site-packages\rest_framework\utils\json.py", line 25, in dumps
return json.dumps(*args, **kwargs)
File "D:\python3\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "D:\python3\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "D:\python3\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
ValueError: Out of range float values are not JSON compliant
我的主要逻辑代码如下,在我的数据字典中有一些nan
值:
class BasicView(viewsets.ModelViewSet):
queryset = ...
serializer_class = ...
filter_backends = ...
renderer_classes = [JSONRenderer, BrowsableAPIRenderer]
@action(methods=['get'], url_path='dash', detail=False)
def dashboard(self, request):
try:
data = a = [{"k": 1, "v": float('nan')}, {"k": 2, "v": float('inf')}]
return Response({"data":data})
except json.decoder.JSONDecodeError:
print(f"empty result with {request.user.id}")
return Response(status=status.HTTP_404_NOT_FOUND)
except:
import traceback as tb
print(tb.format_exc())
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
我怎样才能得到正确的回答?
1条答案
按热度按时间weylhg0b1#
JSON没有
NaN
的概念,它只能表示表示实际数字的数字(它也没有其他浮点数的概念,如无穷大和负零)。您必须确保要序列化为JSON的数据中没有
NaN
浮点数。