How To Convert JSON to Markdown in Python
In this tutorial, we explore different methods to convert JSON to Markdown using Python.
We will cover manual conversion using string manipulation, Pandas for handling tabular data, and specialized libraries like tabulate
for more conversions.
Manual Conversion (String Replacement)
First, let’s start by importing the json
library and defining a sample JSON data structure.
import json json_data = ''' { "user_id": 101, "name": "Jordan", "email": "jordan@example.com", "purchases": [ {"item": "Laptop", "price": 1200}, {"item": "Headphones", "price": 150} ] } ''' data = json.loads(json_data)
Output:
{ 'user_id': 101, 'name': 'Jordan', 'email': 'jordan@example.com', 'purchases': [{'item': 'Laptop', 'price': 1200}, {'item': 'Headphones', 'price': 150}] }
This output shows the JSON data successfully converted into a Python dictionary, making it easier to manipulate.
Next, let’s format this data into Markdown. We’ll create a Markdown string that represents the same data in a human-readable format.
markdown_output = f""" ## User Information - **ID**: {data['user_id']} - **Name**: {data['name']} - **Email**: {data['email']} ## Purchases """ for purchase in data['purchases']: markdown_output += f"- **Item**: {purchase['item']}, **Price**: ${purchase['price']}\n" print(markdown_output)
Output:
## User Information - **ID**: 101 - **Name**: Jordan - **Email**: jordan@example.com ## Purchases - **Item**: Laptop, **Price**: $1200 - **Item**: Headphones, **Price**: $150
Using Pandas
First, let’s import Pandas and convert our JSON data into a Pandas DataFrame.
import pandas as pd import json json_data = ''' { "users": [ {"id": 101, "name": "Jordan", "email": "jordan@example.com"}, {"id": 102, "name": "Alex", "email": "alex@example.com"} ] } ''' data = json.loads(json_data) df = pd.DataFrame(data['users'])
Output:
id name email 0 101 Jordan jordan@example.com 1 102 Alex alex@example.com
Here, the JSON data is converted into a Pandas DataFrame, showing user details in a structured table format.
Now, let’s convert this DataFrame into Markdown format using the to_markdown()
method:
markdown_table = df.to_markdown() print(markdown_table)
Output:
| | id | name | email | |---:|-----:|:-------|:------------------| | 0 | 101 | Jordan | jordan@example.com| | 1 | 102 | Alex | alex@example.com |
Using tabulate
To use the tabulate
library for converting JSON to Markdown in Python, follow these steps:
Install the tabulate
library using pip:
pip install tabulate
Import the necessary functions from the tabulate
module:
from tabulate import tabulate
Prepare your JSON data. Here’s an example JSON:
json_data = [ {"Name": "John Doe", "Age": 30, "City": "New York"}, {"Name": "Jane Smith", "Age": 25, "City": "London"}, {"Name": "Bob Johnson", "Age": 35, "City": "Paris"} ]
Convert the JSON data to a list of lists:
table = [list(item.values()) for item in json_data]
Use the tabulate
function to generate the Markdown table:
markdown = tabulate(table, headers="keys", tablefmt="pipe")
In the tabulate
function, we pass the table
variable as the data to be converted.
The headers="keys"
parameter indicates that the keys of the JSON objects should be used as table headers.
The tablefmt="pipe"
parameter specifies that the output format should be Markdown with pipe-style table borders.
Print or use the markdown
variable as needed:
print(markdown)
The output will be a Markdown table:
| Name | Age | City | |:------------|------:|:----------| | John Doe | 30 | New York | | Jane Smith | 25 | London | | Bob Johnson | 35 | Paris |
You can customize the tabulate
function further by specifying different table formats (plain
, simple
, grid
, fancy_grid
, etc.) and various other options.
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.