Python: How to print a json object in table format

If you have json object and you want print the json object in table format, then you are the right place. Though I didn't wrote any module, I found one which can help. There is a module named pytablewriter. You can use that module to print your json object in many formats, checkout their documenration for more information. Now let's get into business. Lets say you have a json object like below
obj = [{
	'name': 
	'Fix PRB', 
	'project': 
	'PRB', 
	'status': 
	'New', 
	'category': 
	'work', 
	'created_on': 
	'2021-05-13 19:29:39.023231'}, {
	'name': 
	'catalog_broken', 
	'project':  
	'zoom', 
	'status': 
	'New', 
	'category': 
	'work', 
	'created_on': 
	'2021-05-13 19:54:42.109463'}]
We need to build couple of parameters first. Create 3 variables with names as table_name, headers, value_matrix.
table_name = 
	"Todo List"
	# this will not print, its just needed.
headers = []
value_matrix = []
Now lets extract keys and values from given json object.
headers = list(obj[
	0].keys())


	for item 
	in obj:
	value_matrix.append(list(item.values()))
So we built the needed data, now lets print it.
	from pytablewriter 
	import UnicodeTableWriter
writer = UnicodeTableWriter( table_name = table_name, headers = headers, value_matrix = value_matrix )
writer.write_table()
┌──────────────┬───────┬──────┬────────┬──────────────────────────┐
│     name     │project│status│category│        created_on        │
├──────────────┼───────┼──────┼────────┼──────────────────────────┤
│Fix PRB       │PRB    │New   │work    │
	2021
	-05
	-13
	19:
	29:
├──────────────┼───────┼──────┼────────┼──────────────────────────┤
│catalog_broken│zoom   │New   │work    │
	2021
	-05
	-13
	19:
	54:
└──────────────┴───────┴──────┴────────┴──────────────────────────┘
And that's it. It will create a table with give json object. Check the pytablewriter documentation for more options. So I have created a fucntion which you use if you needed in case
	
		def
		pyTablePrinter
		(json_obj, table_name=
			"Todo List")
		:
	

        table_name = table_name
        headers = []
        value_matrix = [] 

        headers = list(json_obj[
	0].keys())
        
	for item 
	in json_obj :
            value_matrix.append(list(item.values()))
        
        writer = UnicodeTableWriter( table_name = table_name, headers = headers, value_matrix = value_matrix )
        writer.write_table()

Hope it helps. Thank you Raja G

0 comments:

Post a Comment