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

前端 未结 6 1991
没有蜡笔的小新
没有蜡笔的小新 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:03

    You can't override the existing encoder for integers...but there might be another way to get what you want. What about something like this:

    import json
    import re
    
    data = {'test': 33, 'this': 99, 'something bigger':[1,2,3, {'a':44}]}  
    s = json.dumps(data, indent=4)
    print(re.sub('(\d+)', lambda i: hex(int(i.group(0))),s))
    

    Results in:

    {
        "test": 0x21,
        "this": 0x63,
        "something bigger": [
            0x1,
            0x2,
            0x3,
            {
                "a": 0x2c
            }
        ]
    }
    

    Note: This isn't especially "robust" (fails on numbers embedded in strings, floats, etc.), but might be good enough for what you want (You could also enhance the regex here so it would work in a few more cases).

提交回复
热议问题