javascript - Parsing datetime in python json loads -


i want parse (json.loads) json string contains datetime values sent http client.

i know can write custom json encoder extending default encoder , overriding default method

class myjsonencoder(json.jsonencoder):     def default(self, obj):         if isinstance(obj, (datetime.datetime,)):             return obj.isoformat()         elif isinstance(obj, (decimal.decimal,)):             return str(obj)         else:             return json.jsonencoder.default(self, obj) 

my questions -

  1. how customize default json decoder? need override decode method? can in way, override/add callback function every field/value in json string? (i have seen code in json.decoder.jsondecoder , json.scanner not sure do)
  2. is there easy way identify specific value datetime string? date values strings in iso format.

thanks,

there other solutions, json.load & json.loads both take object_hook argument1 called every parsed object, return value being used in place of provided object in end result.

combining little tag in object, possible;

import json import datetime import dateutil.parser import decimal  converters = {     'datetime': dateutil.parser.parse,     'decimal': decimal.decimal, }   class myjsonencoder(json.jsonencoder):     def default(self, obj):         if isinstance(obj, (datetime.datetime,)):             return {"val": obj.isoformat(), "_spec_type": "datetime"}         elif isinstance(obj, (decimal.decimal,)):             return {"val": str(obj), "_spec_type": "decimal"}         else:             return super().default(obj)   def object_hook(obj):     _spec_type = obj.get('_spec_type')     if not _spec_type:         return obj      if _spec_type in converters:         return converters[_spec_type](obj['val'])     else:         raise exception('unknown {}'.format(_spec_type))   def main():     data = {         "hello": "world",         "thing": datetime.datetime.now(),         "other": decimal.decimal(0)     }     thing = json.dumps(data, cls=myjsonencoder)      print(json.loads(thing, object_hook=object_hook))  if __name__ == '__main__':     main() 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -