Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1101365
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T01:01:26+00:00 2026-05-17T01:01:26+00:00

import datetime, json x = {‘alpha’: {datetime.date.today(): ‘abcde’}} print json.dumps(x) The above code fails

  • 0
import datetime, json
x = {'alpha': {datetime.date.today(): 'abcde'}}
print json.dumps(x)

The above code fails with a TypeError since keys of JSON objects need to be strings. The json.dumps function has a parameter called default that is called when the value of a JSON object raises a TypeError, but there seems to be no way to do this for the key. What is the most elegant way to work around this?

  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T01:01:27+00:00Added an answer on May 17, 2026 at 1:01 am

    You can extend json.JSONEncoder to create your own encoder which will be able to deal with datetime.datetime objects (or objects of any type you desire) in such a way that a string is created which can be reproduced as a new datetime.datetime instance. I believe it should be as simple as having json.JSONEncoder call repr() on your datetime.datetime instances.

    The procedure on how to do so is described in the json module docs.

    The json module checks the type of each value it needs to encode and by default it only knows how to handle dicts, lists, tuples, strs, unicode objects, int, long, float, boolean and none 🙂

    Also of importance for you might be the skipkeys argument to the JSONEncoder.


    After reading your comments I have concluded that there is no easy solution to have JSONEncoder encode the keys of dictionaries with a custom function. If you are interested you can look at the source and the methods iterencode() which calls _iterencode() which calls _iterencode_dict() which is where the type error gets raised.

    Easiest for you would be to create a new dict with isoformatted keys like this:

    import datetime, json
    
    D = {datetime.datetime.now(): 'foo',
         datetime.datetime.now(): 'bar'}
    
    new_D = {}
    
    for k,v in D.iteritems():
      new_D[k.isoformat()] = v
    
    json.dumps(new_D)
    

    Which returns ‘{“2010-09-15T23:24:36.169710”: “foo”, “2010-09-15T23:24:36.169723”: “bar”}’. For niceties, wrap it in a function 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is my code: import datetime today = datetime.date.today() print(today) This prints: 2008-11-22 which
MyCalendar.py Code: from django import template imort calendar import datetime date = datetime.date.today() week
This code: import datetime d_tomorrow = datetime.date.today() + datetime.timedelta(days=1) class Model(models.Model): ... timeout =
My code: import datetime as dt import scikits.timeseries as ts ts_start_datetime= ts.Date(freq='T',year=2011,month=1,day=1,hour= 0,minute=0) ts_end_datetime
def display_home(request): from datetime import * now=datetime.today() print 'Month is %s'%now.month events=Event.objects.filter(e_date__year=datetime.today().year).filter(e_date__month=datetime.today().month,e_status=1).values('e_name','e_date') return render_to_response("SecureVirtualElection/home.html",{'events':
import sqlite3 import datetime today = datetime.date.today() db_name = test.db db = sqlite3.connect(db_name, detect_types=sqlite3.PARSE_DECLTYPES)
Using import datetime in python, is it possible to take a formatted time/date string
Code: class JobsManager(models.Manager): def get_active_by_category(self, cat, limit): import datetime from django.db.models import Q return
import datetime start = datetime.datetime(2009, 1, 31) end = datetime.datetime(2009, 2, 1) print end-start
I start out with date strings: from operator import itemgetter import datetime as DT

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.