Damien Sullivan (mindstalk) wrote,
Damien Sullivan
mindstalk

python JSON datetime at last

content warning: geeky computer stuff

At work I have a common flow of Python code querying MySQL and dumping results into JSON. This works great except our tables tend to have columns for create and modify dates. And Python's json library won't convert datetime types to string, so dumping the result of "SELECT * FROM" errors. And I've had bits of ad hoc code to remote datetime values, then a little function for it, but it was still a pain. Especially today, when for stupid VPC reasons I'm writing a simple generic SQL service.

In annoyance I tried searching again and found, buried in the middle of a stackoverflow with answers about subclassing and shit:

json.dumps(thing, default=str)

Bam, done. The function passed to 'default' gets invoked on anything that errors at first. And in Python 'str' works on pretty much anything.

If I cared about the exact format I could write a function that inspected type and converted dates (or just assume datetime is the only cause of errors so just invoke a method when triggered), but str is fine for now.

Soooo simple. Thanks, python, and stackoverflow person who gave the simplest answer. See the comment count unavailable DW comments at https://mindstalk.dreamwidth.org/582101.html#comments
Tags: programming, python
Subscribe

  • more Javascript

    New Job has me learning JS and Node.js. I have learned that some of my earlier complaints (see tag) have been improved by later developments (or ones…

  • watermarking ebooks

    I've bought RPG PDFs. They're never DRMed, but from DriveThruRPG they're allegedly watermarked. I've bought DRM-free ebooks. Watermarking isn't…

  • JS surprise

    I was looking at my 'programming' tag posts and found a bunch of 3 years ago, complaining about odd features of JavaScript. I kind of remember them…

  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments