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

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

    You could always reparse the json, where you do have some control over int parsing, so that you can override int repr:

    class hexint(int):
       def __repr__(self):
         return "0x%x" % self
    
    json.loads(json.dumps(data), parse_int=hexint)
    

    And using the data as in Gerrat's answer, the output is:

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

提交回复
热议问题