Workaround for JSON not serializing DateTime in Django

Source: Internet
Author: User

Tag: DateTime ref opened cannot be a none char members backstage. JSON

  

We often in the design of the Web page in front and back-end interaction, the front-end callback method can be redirect an address with explicit parameters, the second way is to use the AJAX structure. Then, after uploading to the view function, it is necessary to return to the front end in JSON format, or the front end is not aware of the returned data, it is necessary to use the serialization of JSON.

If the data that is taken from the database is often queryset type, JSON cannot be serialized directly, it needs to be converted to a list in the form of JSON, which solves most of the problems, but if the data contains a datetime type JSON, it will be error-based. It cannot be serialized and appears as follows:

  

Look at the source code, where is the problem?

From the source code we can see that JSON can only serialize data of type Str. So there's no other way?

Method One

Let's look at the source code again:

defDumps (obj, *, Skipkeys=false, ensure_ascii=true, check_circular=True, Allow_nan=true, Cls=none, Indent=none, separators=None, default=none, Sort_keys=false, * *kw):"""Serialize ' obj ' to a JSON formatted ' str '. If ' Skipkeys ' is true Then ' dict ' Keys ', ' Am not basic types (' str ', ' ' int ', ' ' float ', ' bool ', ' None ') w    Ill be skipped instead of raising a ' TypeError '. If ' Ensure_ascii ' is false and then the return value can contain non-ascii characters if they appear in strings Containe D in ' obj '.    Otherwise, all such characters is escaped in JSON strings. If ' Check_circular ' is false, then the circular reference check for container types would be skipped and a circular re    Ference would result in an ' overflowerror ' (or worse). If ' Allow_nan ' is false and then it'll be a "valueerror" to serialize out of range ' float ' values (' Nan ', ' inf ') ', '-inf ') in strict compliance of the JSON specification, instead of using the JavaScript equivalents (' NaN ', '    ' Infinity ', '-infinity '). If ' indent ' is a non-negative integer, then JSON array elements and object members'll be Pretty-printeD with the indent level. An indent level of 0 would only insert newlines.    ' None ' is the most compact representation.  If specified, ' separators ' should is an ' (Item_separator, Key_separator) ' tuple.  The default is ' ' (', ', ': ') ' If *indent* is ' ' None ' and ' ' (', ', ': ') ' otherwise.    To get the most compact JSON representation, you should specify "(', ', ': ') ' to eliminate whitespace. ' Default (obj) ' is a function, that should return a serializable version of obj or raise TypeError.    The default simply raises TypeError.    If *sort_keys* is True (default: "False"), then the output of dictionaries would be sorted by key. To use a custom "Jsonencoder" subclass (e.g. one that overrides the ". Default ()" method to serialize additional Typ ES), specify it with the ' CLS ' Kwarg;     Otherwise ' jsonencoder ' is used."""    #Cached Encoder    if( notSkipkeys andEnsure_ascii andCheck_circular andAllow_nan andCLS isNone andIndent isNone andSeparators isNone anddefault isNone and  notSort_keys and  notkw):return_default_encoder.encode (obj)ifCls isNone:cls=JsonencoderreturnCLS (Skipkeys=skipkeys, ensure_ascii=Ensure_ascii, Check_circular=check_circular, Allow_nan=allow_nan, indent=indent, separators=separators, Default=default, sort_keys=Sort_keys,**kw). Encode (obj) _default_decoder= Jsondecoder (Object_hook=none, Object_pairs_hook=none)
Json.dumps Source

It mentions:

So we can try to customize the Jsonencoder:

class Cjsonencoder (self,o):     if isinstance (o,datetime.datetime):         return o.strftime ("%y-%m-%d%h-%m-%s")    if  Isinstance (o,datetime.date):        return o.strftime ("%y-%m-%d"  )    else: reture json. Jsonencoder.default (Self,o)

Then use json.dumps (data,cls = cjsonencoder) in JSON serialization

  

Method 2:

If you don't have a foreign key when you fetch a database, you can also use the Django built-in method: serializers in Import Django.core, dedicated to serializing Queryset class data = Serializers.serialize ( ' JSON ', Data ' directly can serialize the Queryset, limited in with the foreign key support is not good enough.

  

Workaround for JSON not serializing DateTime in Django

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.