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

I am currently using the following code to print a large data structure

print(json.dumps(data, indent=4))

I would like to see all integers that print in hex instead of decimal. Is it possible? It seems that there is no way to override the existing encoder for integers. You can only provide default types that are no longer processed by the JSONEncoder class, but cannot override how it encodes integers.

I realized that I can override the default behavior of an integer using sys.displayhook if I worked on the command line, but I do not.

Just for reference, the data structure is a bag with bags of dicts, lists, string, ints, etc. So I went with json.dumps (). The only other way I can think of is to parse it myself, and then I will rewrite the json module.

Update: Therefore, I ended up implementing it using serialization functions that simply print a copy of the original data structure with all integer types converted to hexadecimal strings:

def odprint(self, hexify=False):
    """pretty print the ordered dictionary"""
    def hexify_list(data):
        _data = []
        for i,v in enumerate(data):
            if isinstance(v, (int,long)):
                _data.insert(i,hex(v))
            elif isinstance(v,list):
                _data.insert(i, hexify_list(v))
            else:
                _data.insert(i, val)
        return _data

    def hexify_dict(data):
        _data = odict()
        for k,v in data.items():
            if isinstance(v, (dict,odict)):
                _data[k] = hexify_dict(v)
            elif isinstance(v, (int, long)):
                _data[k] = hex(v)
            elif isinstance(v,list):
                _data[k] = hexify_list(v)
            else:
                _data[k] = v
        return _data

    if hexify:
        print(json.dumps(hexify_dict(self), indent=4))
    else:
        print(json.dumps(self, indent=4))

Thanks for the help. I understand that I end up making a reservation with a standard dict, but its just printable so good that I need to.

+5
source share
6 answers

, serialize, " " json . :

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)

:

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

, , .

, , . , , , , () JSON (b) JSON .

.

+2

JSON.

YAML.

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

:

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}
+2

... , . - :

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))

:

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

. "" ( , , ..), , ( , ).

+1

Python 2.7, :

import __builtin__

_orig_str = __builtin__.str

def my_str(obj):
    if isinstance(obj, (int, long)):
        return hex(obj)
    return _orig_str(obj)
__builtin__.str = my_str

import json 

data = {'a': [1,2,3], 'b': 4, 'c': 16**20}
print(json.dumps(data, indent=4))

:

{
    "a": [
        0x1,
        0x2,
        0x3
    ],
    "c": 0x100000000000000000000L,
    "b": 0x4
}

Python 3 __builtin__ builtins, (ideone.com ImportError: libz.so.1...)

0

json, int parsing, int repr:

class hexint(int):
   def __repr__(self):
     return "0x%x" % self

json.loads(json.dumps(data), parse_int=hexint)

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

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

Single liner

If you don't mind your hexadecimal strings, use this single line font:

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

Output (using Gerrat again data):

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

This is a better answer than my previous post, as I was dealing with getting a printed result.

0
source

All Articles