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

前端 未结 6 1990
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  旧时难觅i
    2021-01-05 18:08

    One-liner

    If you don't mind your hex strings quoted, use this one-liner:

    print(json.dumps(eval(str(json.loads(json.dumps(data), parse_int=lambda i:hex(int(i))))), indent=4))
    

    Output (using Gerrat's data again):

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

    This is a better answer than my previous post as I've dealt with getting a pretty-printed result.

提交回复
热议问题