Skip to content

Instantly share code, notes, and snippets.

@pavan538
Forked from simonw/gist:7000493
Last active April 3, 2019 10:19
Show Gist options
  • Select an option

  • Save pavan538/d10e415216e0d718733c28d616bc2c77 to your computer and use it in GitHub Desktop.

Select an option

Save pavan538/d10e415216e0d718733c28d616bc2c77 to your computer and use it in GitHub Desktop.

Revisions

  1. pavan538 renamed this gist Apr 3, 2019. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. pavan538 revised this gist Apr 3, 2019. 1 changed file with 3 additions and 2 deletions.
    5 changes: 3 additions & 2 deletions gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -18,7 +18,8 @@ def default(self, obj):
    "dt": datetime.datetime(2013, 11, 11, 10, 40, 32)
    }

    print json.dumps(data, cls=RoundTripEncoder, indent=2)
    print (json.dumps(data, cls=RoundTripEncoder, indent=2))


    import json, datetime
    from dateutil import parser
    @@ -35,5 +36,5 @@ def object_hook(self, obj):
    return parser.parse(obj['value'])
    return obj

    print json.loads(s, cls=RoundTripDecoder)
    print (json.loads(s, cls=RoundTripDecoder))

  3. @simonw simonw created this gist Oct 15, 2013.
    39 changes: 39 additions & 0 deletions gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    import json, datetime

    class RoundTripEncoder(json.JSONEncoder):
    DATE_FORMAT = "%Y-%m-%d"
    TIME_FORMAT = "%H:%M:%S"
    def default(self, obj):
    if isinstance(obj, datetime.datetime):
    return {
    "_type": "datetime",
    "value": obj.strftime("%s %s" % (
    self.DATE_FORMAT, self.TIME_FORMAT
    ))
    }
    return super(RoundTripEncoder, self).default(obj)

    data = {
    "name": "Silent Bob",
    "dt": datetime.datetime(2013, 11, 11, 10, 40, 32)
    }

    print json.dumps(data, cls=RoundTripEncoder, indent=2)

    import json, datetime
    from dateutil import parser

    class RoundTripDecoder(json.JSONDecoder):
    def __init__(self, *args, **kwargs):
    json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)

    def object_hook(self, obj):
    if '_type' not in obj:
    return obj
    type = obj['_type']
    if type == 'datetime':
    return parser.parse(obj['value'])
    return obj

    print json.loads(s, cls=RoundTripDecoder)