Last active
January 6, 2022 21:12
-
-
Save asyd/1cee3bc4c1d40b64fb25a7fa5bad631a to your computer and use it in GitHub Desktop.
Display JSON array as table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse | |
import json | |
import csv | |
from rich.console import Console | |
from rich.table import Table | |
import sys | |
def main(args): | |
data = None | |
# Convert JSON inputs as | |
try: | |
data = json.loads(sys.stdin.read()) | |
except json.decoder.JSONDecodeError: | |
print("Invalid input", file=sys.stderr) | |
sys.exit(1) | |
if data.__class__ is not list: | |
print("JSON input is not a list") | |
sys.exit(2) | |
# Extract keys from first record | |
headers = data[0].keys() | |
if args.rich: | |
table = Table(show_header=True, header_style='bold blue') | |
for index, header in enumerate(headers): | |
if index == 0: | |
color = 'green' | |
else: | |
color = 'cyan' | |
table.add_column(header, style=color) | |
for row in data: | |
table.add_row(*list(row.values())) | |
console = Console() | |
console.print(table) | |
else: | |
writer = csv.DictWriter(sys.stdout, delimiter=',', fieldnames=headers) | |
writer.writeheader() | |
for row in data: | |
writer.writerow(row) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--rich', action='store_true', default=False) | |
args = parser.parse_args() | |
main(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment