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 integers that get printed in hex instead of decimal. Is that possible? It seems that there is no way to override the existing encoder for integers. You can only provide a default for types not already handled by the JSONEncoder class, but no way to override how it encodes integers.
I figured out I can override the default integer printing behavior using sys.displayhook if I was running in the command line but I am not.
Just for reference the data structure is a mix bag of dicts, lists, strings, ints, etc. So that is why I went with the json.dumps(). The only other way I can think of doing it is to parse it myself and then I would be re-writing the json module.
Update: So I ended up implementing it with serializing functions that just print a copy of the original data structure with all integer types converted to hex 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 realize that I end up making an odict from a standard dict, but its just for printing so its fine for what I need.
else:makes sure that it doesn't loose data except that it erases the difference between a string/integer with hex digits. I've overlooked that. But it doesn't convert data that it should convert e.g.,hexify_list()doesn't callhexify_dict().tuples are ignored. btw, don't use.insert(i, item), use.append(item).insertvs.append, why say "don't" use? Is it a performance thing?