How to print integers as hex strings using json.dumps() in Python

前端 未结 6 2005
没有蜡笔的小新
没有蜡笔的小新 2021-01-05 17:18

Currently I am using the following code to print a large data structure

print(json.dumps(data, indent=4))

I would like to see all the integ

6条回答
  •  感动是毒
    2021-01-05 18:18

    Dirty hack for Python 2.7, I wouldn't recomend to use it:

    import __builtin__
    
    _orig_str = __builtin__.str
    
    def my_str(obj):
        if isinstance(obj, (int, long)):
            return hex(obj)
        return _orig_str(obj)
    __builtin__.str = my_str
    
    import json 
    
    data = {'a': [1,2,3], 'b': 4, 'c': 16**20}
    print(json.dumps(data, indent=4))
    

    Output:

    {
        "a": [
            0x1,
            0x2,
            0x3
        ],
        "c": 0x100000000000000000000L,
        "b": 0x4
    }
    

    On Python 3 __builtin__ module is now builtins, but I can't test it (ideone.com fails with ImportError: libz.so.1 ...)

提交回复
热议问题