Skip to content

Instantly share code, notes, and snippets.

@tenekev
Created August 27, 2024 10:46
Show Gist options
  • Save tenekev/436f8403b843fc060235dd3c3f9d5aed to your computer and use it in GitHub Desktop.
Save tenekev/436f8403b843fc060235dd3c3f9d5aed to your computer and use it in GitHub Desktop.
A Python function that transforms a list of dicts (a list of json objects) to a markdown table. It also accepts a format schema - custom order and labels. It can be transposed. (Swap row and column)
def converter__json_to_md_table(json_data:list, formated:list=None, transposed:bool=True) -> str:
"""
Converts JSON data to a Markdown table with optional key order, key labels and transposition.
Parameters:
- json_data: list(dict): Reqired: The JSON data as a list of dictionaries.
json_data = [
{key_1:value, key_2:value, key_3:value},
{key_1:value, key_2:value, key_3:value},
...
]
- formated: list(dict(str)): Optional: A dict specifying the custom order and labels of keys.
Default is None.
formated = { Order is preserved as of python >=3.7
'key_1': 'label', | 0
'key_2': 'Key Two' | 1
. . . V 3
}
- transposed: bool: Optional. If True, transposes rows and columns.
Default is True.
Returns:
- str: Markdown formatted table.
"""
# Ensure proper data types are supplied
if not isinstance(json_data, list) or not all(isinstance(item, dict) for item in json_data):
raise ValueError("Input data must be a list of dictionaries.")
if formated:
if not isinstance(formated, dict) or not all(isinstance(item, str) for item in formated):
raise ValueError("Input data must be a dict of strings.")
# Determine the keys (headers) to be used
keys_in_data = set()
for item in json_data:
keys_in_data.update(item.keys())
key_order = list()
key_labels = list()
if formated is None:
key_order = sorted(keys_in_data)
key_labels = sorted(keys_in_data)
else:
for key, label in formated.items():
if key in keys_in_data:
key_order.append(key)
key_labels.append(label)
# Generate the Markdown table
table = []
if transposed:
for index, key in enumerate(key_order):
row = [f"**{key_labels[index]}**"]
row.extend(str(item.get(key, "")) for item in json_data)
table.append("| " + " | ".join(row) + " |")
if index == 0:
separator_row = "| " + " | ".join(["---"] * (len(json_data) + 1) ) + " |"
table.append(separator_row)
else:
header_row = "| " + " | ".join(key_labels) + " |"
separator_row = "| " + " | ".join(["---"] * len(key_order)) + " |"
table.append(header_row)
table.append(separator_row)
for item in json_data:
row = "| " + " | ".join(str(item.get(key, "")) for key in key_order) + " |"
table.append(row)
# Join all rows into a single string
return "\n".join(table)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment