我使用djangorestframework生成API,我的Serializer为:
from rest_framework import serializers
class MarketSerializer(serializers.Serializer):
total_market_cap = serializers.FloatField(read_only=True)
volume = serializers.FloatField(required=False)
turnover_rate = serializers.FloatField(required=False)
pe = serializers.FloatField(required=False)
class MarketOverallSerializer(serializers.Serializer):
# markets = MarketSerializer(many=True) # A nested list of 'edit' items.
sh = MarketSerializer()
sz = MarketSerializer()
cyb = MarketSerializer()
zxb = MarketSerializer()
我的APIView为:
import json
from django.shortcuts import render
# Create your views here.
from rest_framework.renderers import JSONRenderer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from serializers import MarketSerializer, MarketOverallSerializer
from market.models import Market
from market.parse import *
class MarketView(APIView):
def get(self, request, *args, **kw):
# Process any get params that you may need
# If you don't need to process get params,
# you can skip this part
market = market_overall()
serializer = MarketOverallSerializer(market)
content = JSONRenderer().render(serializer.data)
print '**********content:{}'.format(content)
response = Response(content, status=status.HTTP_200_OK)
return response
我得到JSON响应:
"{\"sh\":{\"total_market_cap\":262143.47,\"volume\":25240015.73,\"turnover_rate\":0.84,\"pe\":15.8},\"sz\":{\"total_market_cap\":0.0,\"volume\":0.0,\"turnover_rate\":0.0,\"pe\":0.0},\"cyb\":null,\"zxb\":null}"
为什么生成的响应不是有效的JSON输出,有这么多“\”字符?
答案 0 :(得分:2)
原因是DRF中的默认渲染器是json(ref:http://www.django-rest-framework.org/api-guide/renderers/#setting-the-renderers)。
因此,每次使用DRF' Response
时,您应该直接传递dict而不是渲染json。
在你的情况下,通过一次又一次渲染json(使用Response
),json内置模块会转义特殊字符并将其视为单个字符串(这就是json.loads()
给出的原因回到适当的json)
所以修复它的方法是:
JSONRenderer
,只需将字典直接传递给Response
JSONRenderer
,然后专门告诉Response
使用text/html
作为内容类型。