Solve Python's own JSON does not serialize Data,datetime type data problems

Source: Internet
Author: User

A demo in the official documentation:

>>> Import json>>> class Complexencoder (JSON. Jsonencoder):     ... def default (self, obj): ...         If Isinstance (obj, complex): ...             return [Obj.real, Obj.imag]         ... Return JSON. Jsonencoder.default (self, obj) ...>>> dumps (2 + 1j, Cls=complexencoder) ' [2.0, 1.0] ' >>> Complexencoder (). Encode (2 + 1j) ' [2.0, 1.0] ' >>> list (Complexencoder (). Iterencode (2 + 1j)) [' [', ' 2.0 ', ', ', ' 1.0 ‘, ‘]‘]

Then simply extend a jsonencoder out to format the time

Class Cjsonencoder (JSON. Jsonencoder):    def default (self, obj):        if Isinstance (obj, datetime):            return Obj.strftime ('%y-%m-%d%h:%m: %s ')        elif isinstance (obj, date):            return obj.strftime ('%y-%m-%d ')        else:            return JSON. Jsonencoder.default (self, obj)

When using, simply add a CLS parameter to the Json.dumps:

Json.dumps (DataList, Cls=cjsonencoder)

If you do not want to define a class, you can format it directly after the date or DateTime object we get, using the Strftime method.

Solve Python's own JSON does not serialize Data,datetime type data problems

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.