Zoyinc
  • Home
  • Contact
  • Categories
    • CD Archiving
    • GIMP
    • Linux
    • MythTV
    • Open Media Vault
    • Technology
    • VMware
    • WordPress
    • YouTube
  • About


Date Problems Converting A Dictionary To JSON

By

Tony

,

June 3, 2019

If you want to convert a dictionary object to JSON you would use something like:

myJSON = json.dumps(myDict, indent=4, sort_keys=True)

So if we have a simple script that looks like:

import datetime
import json

JimStartTate = '21/12/2019 08:30'
JimLunchTime = '21/12/2019 12:00'
JimHomeTime = '21/12/2019 17:30'
FredStartTate = '21/12/2019 10:30'
FredLunchTime = '21/12/2019 13:00'
FredHomeTime = '21/12/2019 15:30'
myDict =    {'jim':
                {'start_time':JimStartTate,
                 'lunch_time':JimLunchTime,
                 'home_time':JimHomeTime,
                 'age':31},
            'fred':
                {'start_time':FredStartTate,
                 'lunch_time':FredLunchTime,
                 'home_time':FredHomeTime,
                 'age':20}
            }

print(json.dumps(myDict, indent=4, sort_keys=True))

This produces:

C:\Projects\Examples>python json_dump_std.py
{
    "fred": {
        "age": 20,
        "home_time": "21/12/2019 15:30",
        "lunch_time": "21/12/2019 13:00",
        "start_time": "21/12/2019 10:30"
    },
    "jim": {
        "age": 31,
        "home_time": "21/12/2019 17:30",
        "lunch_time": "21/12/2019 12:00",
        "start_time": "21/12/2019 08:30"
    }
}

But things get complicated when we use dates rather than strings:

import datetime
import json

JimStartTate = datetime.datetime.strptime('21/12/2019 08:30', '%d/%m/%Y %H:%M')
JimLunchTime = datetime.datetime.strptime('21/12/2019 12:00', '%d/%m/%Y %H:%M')
JimHomeTime = datetime.datetime.strptime('21/12/2019 17:30', '%d/%m/%Y %H:%M')
FredStartTate = datetime.datetime.strptime('21/12/2019 10:30', '%d/%m/%Y %H:%M')
FredLunchTime = datetime.datetime.strptime('21/12/2019 13:00', '%d/%m/%Y %H:%M')
FredHomeTime = datetime.datetime.strptime('21/12/2019 15:30', '%d/%m/%Y %H:%M')
myDict =    {'jim':
                {'start_time':JimStartTate,
                 'lunch_time':JimLunchTime,
                 'home_time':JimHomeTime,
                 'age':31},
            'fred':
                {'start_time':FredStartTate,
                 'lunch_time':FredLunchTime,
                 'home_time':FredHomeTime,
                 'age':20}
            }

print(json.dumps(myDict, indent=4, sort_keys=True))

Which instead produces:

C:\Projects\Examples>python json_dump.py
Traceback (most recent call last):
File "json_dump.py", line 22, in <module>
print(json.dumps(myDict, indent=4, sort_keys=True))
File "C:\Python\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Python\lib\json\encoder.py", line 201, in encode
chunks = list(chunks)
File "C:\Python\lib\json\encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "C:\Python\lib\json\encoder.py", line 405, in _iterencode_dict
yield from chunks
File "C:\Python\lib\json\encoder.py", line 405, in _iterencode_dict
yield from chunks
File "C:\Python\lib\json\encoder.py", line 438, in _iterencode
o = _default(o)
File "C:\Python\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: <span style="background-color: #ffff00;">Object of type datetime is not JSON serializable</span>

Simple answer provided by jjmontes in a stackoverflow post:

https://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable

Is to change it to: json.dumps(myDict, indent=4, sort_keys=True, default=str)

Thus giving:

import datetime
import json

JimStartTate = datetime.datetime.strptime('21/12/2019 08:30', '%d/%m/%Y %H:%M')
JimLunchTime = datetime.datetime.strptime('21/12/2019 12:00', '%d/%m/%Y %H:%M')
JimHomeTime = datetime.datetime.strptime('21/12/2019 17:30', '%d/%m/%Y %H:%M')
FredStartTate = datetime.datetime.strptime('21/12/2019 10:30', '%d/%m/%Y %H:%M')
FredLunchTime = datetime.datetime.strptime('21/12/2019 13:00', '%d/%m/%Y %H:%M')
FredHomeTime = datetime.datetime.strptime('21/12/2019 15:30', '%d/%m/%Y %H:%M')
myDict =    {'jim':
                {'start_time':JimStartTate,
                 'lunch_time':JimLunchTime,
                 'home_time':JimHomeTime,
                 'age':31},
            'fred':
                {'start_time':FredStartTate,
                 'lunch_time':FredLunchTime,
                 'home_time':FredHomeTime,
                 'age':20}
            }

print(json.dumps(myDict, indent=4, sort_keys=True, default=str))

Which gives the desired result:

{
    "fred": {
        "age": 20,
        "home_time": "2019-12-21 15:30:00",
        "lunch_time": "2019-12-21 13:00:00",
        "start_time": "2019-12-21 10:30:00"
    },
    "jim": {
        "age": 31,
        "home_time": "2019-12-21 17:30:00",
        "lunch_time": "2019-12-21 12:00:00",
        "start_time": "2019-12-21 08:30:00"
    }
}
Related

Send JSON requests to a VSTS service hook using SoapUI
Persisting Azure Pipeline Variables
Converting FLAC to ALAC using xrecode
CentOS 7 + PHP 7.2 + Python 3.6 + Apache 2.4
Recent

  • AlmaLinux GUI – no taskbar or application shortcuts

    AlmaLinux GUI – no taskbar or application shortcuts

  • AlmaLinux 9.5 base VM

    AlmaLinux 9.5 base VM

  • Reset Kodi thumbnails

    Reset Kodi thumbnails

  • Set default settings values in Kodi skins

    Set default settings values in Kodi skins

  • Add/Remove/Reset music/video libraries in Kodi

    Add/Remove/Reset music/video libraries in Kodi

  • Zoyinc Kodi skin on Sony TV

    Zoyinc Kodi skin on Sony TV

  • [L] – WordPress UAM Locked Post

    [L] – WordPress UAM Locked Post

  • Import Pictures and Videos – images not previewed

    Import Pictures and Videos – images not previewed

  • Find My Train

    Find My Train

  • WordPress style name not visible

    WordPress style name not visible

About Zoyinc

  • Contact Us
  • Zoyinc Disclaimer
  • Google Search Console
  • Privacy Policy
  • Site Statistics
  • Login

Apache Auckland Backup CD CentOS Centos7 Children Configuration Debian Error ESX ESXi Fedora Firewall Install Josh Kids Kodi Linux MariaDB MySQL MythTV New Zealand OKD OMV Open Media Vault OpenShift PHP Player Python RAID RedHat Red Hat Rip School Setup SMB SonicWALL Spark tags Train Trains VLAN VM VMware Weaver Windows WordPress YouTube

Powered by

This site is licensed under a Creative Commons Attribution 4.0 International License.