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

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

    A possible approach is to have a serialize function, which produces a copy of your dictionary on the fly and uses the standard json module to dump the string. A preliminary implementation looks like:

    import json
    
    def serialize(data):
        _data = {}
        for k, v in data.items():
            if isinstance(v, int):
                _data[k] = hex(v)
            else:
                _data[k] = v
        return json.dumps(_data, indent=4)
    
    
    if __name__ == "__main__":
        data = {"a":1, "b":2.0, "c":3}
        print serialize(data)
    

    output:

    {
        "a": "0x1", 
        "c": "0x3", 
        "b": 2.0
    }
    

    Notice that this preliminary implementation does not work with lists, but this is easily changed.

    Some may claim that the approach is memory-intensive because it creates a copy of the original data. This may be the case, but if your data structure is that big, then maybe you should (a) not be using JSON, or (b) create a copy of the JSON module in your working directory and tailor it to your needs.

    Cheers.

提交回复
热议问题