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

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

    Octal and hexadecimal formats are not supported in JSON.

    You could use YAML instead.

    >>> import json, yaml
    >>> class hexint(int):
    ...     def __str__(self):
    ...         return hex(self)
    ...
    >>> json.dumps({"a": hexint(255)})
    '{"a": 0xff}'
    >>> yaml.load(_)
    {'a': 255}
    

    Or without wrapping integers:

    import yaml
    
    def hexint_presenter(dumper, data):
        return dumper.represent_int(hex(data))
    yaml.add_representer(int, hexint_presenter)
    
    print yaml.dump({"a": 255}), # -> {a: 0xff}
    assert yaml.load('{a: 0xff}') == {"a": 255}
    

提交回复
热议问题