----小编在写项目的时候,发现django的JsonResponse很难搞,就上网上搜,但是搜来搜去发现每个都不全面,所以小编在这就整理了一下,希望能给你带来帮助
三个方面入手:
- 参数(self, data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
- data:传入的需要序列化的对象,默认是字典类型, 例: JsonResponse(dict)
- safe:默认值参数,当它为true时,data只能是字典类型,为false时,就可以为任何可以转换为json格式的对象(list,tuble)
- encoder:执行DjangoJSONEncoder类,这个类继承(json.JSONEncoder),因为json转换的数据对象有限,所以DjangoJSONEncoder重写了defalut方法,里面进行对时间对象的转换成json格式;
- json_dumps_params:参数是一个字典,它将调用json.dums,并将参数传给该方法,也就是调用原来json的本身的参数和方法;
- 返回值
- return super(DjangoJSONEncoder, self).default(o)
- 核心思想:
- 本身继承json.JSONEncoder,因为JSONEncoder可转换的数据格式有限,所以DjangoJSONEncoder重写了default方法,该方法里对时间对象进行了转换,而json_dumps_params可以给本身dumps传入参数\
- 源码:
-
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs): if safe and not isinstance(data, dict): raise TypeError( 'In order to allow non-dict objects to be serialized set the ' 'safe parameter to False.' ) if json_dumps_params is None: json_dumps_params = {} kwargs.setdefault('content_type', 'application/json') data = json.dumps(data, cls=encoder, **json_dumps_params) super(JsonResponse, self).__init__(content=data, **kwargs)
class DjangoJSONEncoder(json.JSONEncoder): """ JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs. """ def default(self, o): # See "Date Time String Format" in the ECMA-262 specification. if isinstance(o, datetime.datetime): r = o.isoformat() if o.microsecond: r = r[:23] + r[26:] if r.endswith('+00:00'): r = r[:-6] + 'Z' return r elif isinstance(o, datetime.date): return o.isoformat() elif isinstance(o, datetime.time): if is_aware(o): raise ValueError("JSON can't represent timezone-aware times.") r = o.isoformat() if o.microsecond: r = r[:12] return r elif isinstance(o, datetime.timedelta): return duration_iso_string(o) elif isinstance(o, decimal.Decimal): return str(o) elif isinstance(o, uuid.UUID): return str(o) elif isinstance(o, Promise): return six.text_type(o) elif isinstance(o, CallableBool): return bool(o) else: return super(DjangoJSONEncoder, self).default(o)