Damien Sullivan (mindstalk) wrote,
Damien Sullivan

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

  • Quebec City resisted the Americans but was conquered by the car

    I'm in Quebec City now, as of a few days ago. The train ride was okay. Luggage wasn't as strict as a Not Just Bikes video made me fear: someone did…

  • random observations

    North Oakland has become rather aggressive about traffic calming on residential streets. Lots of circular planters in intersections, like a…

  • travel update

    Been a while. In the long ago golden age of "early June", it was possible to believe the world was going back to normal, and I reserved a really…

  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded