Javascript 在python json加载中解析datetime

Javascript 在python json加载中解析datetime,javascript,python,json,datetime,Javascript,Python,Json,Datetime,我想解析(json.loads)一个json字符串,该字符串包含从http客户端发送的日期时间值 我知道我可以通过扩展默认编码器并重写默认方法来编写自定义json编码器 class MyJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (datetime.datetime,)): return obj.isoformat() elif

我想解析(json.loads)一个json字符串,该字符串包含从http客户端发送的日期时间值

我知道我可以通过扩展默认编码器并重写默认方法来编写自定义json编码器

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)
我的问题是-

  • 如何定制默认的json解码器?我需要覆盖吗 解码方法?我能否以某种方式覆盖/添加回调 json字符串中每个字段/值的函数?(我在json.decoder.JSONDecoder和json.scanner中看到了代码,但不确定该怎么做)
  • 是否有一种简单的方法将特定值标识为日期时间字符串?日期值是ISO格式的字符串

  • 谢谢,

    至于第二个问题,你可能只需要使用
    import dateutil.parser
    dateutil.parser.parse('Your string')

    方法,它将尝试解析您的日期字符串,如果无法识别它,它将抛出值错误。您还可以使用正则表达式来查找至少看起来像日期的字段(当然,这取决于您使用的格式)

    可能还有其他解决方案,但是
    json.load
    &
    json.load
    都使用一个
    object\u hook
    参数,每个解析的对象都会调用该参数,在最终结果中使用其返回值代替提供的对象

    将其与对象中的一个小标记相结合,这样的事情是可能的

    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()
    

    您是否建议我对所有值应用正则表达式?我需要迭代从json字符串获得的整个dict,以便对每个值应用正则表达式?谢谢Dominic。这是有道理的。我想创建一个带有“type”attr的对象,但没有注意到object\u hook参数。