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.