Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Pretty print json in python

For python2 I wanted to show what variables are in use in a function, and I wanted to see it in a nicer format than a really long, single line.

import inspect, json
def function():
print json.dumps(locals(),indent=3,separators=(',',': '))

Bonus

To view what parameters were passed in to a function, add these.

def caller_args():
   frame = inspect.currentframe()
   outer_frames = inspect.getouterframes(frame)
   caller_frame = outer_frames[1][0]
   return inspect.getargvalues(caller_frame)

def function():
print caller_args()

References

  1. https://stackoverflow.com/questions/29935276/inspect-getargvalues-throws-exception-attributeerror-tuple-object-has-no-a#29935277
  2. compact encoding https://docs.python.org/2/library/json.html

Comments