想過把 Markdown 文件自動拆解成結構化資料,方便進行分析或轉換嗎?這篇教學會帶你用 mistune 這個輕量級解析器,把 Markdown 轉成 AST(抽象語法樹),再輸出為 JSON 格式,方便後續自動化處理!
步驟簡介
- 安裝 mistune
- 準備 Markdown 檔案
- 撰寫 Python 程式,解析並輸出 JSON
- 檢視結果
1. 安裝 mistune
在終端機輸入:
pip install mistune
2. 準備 Markdown 檔案
建立一個 sample.md
,內容如: sample.md
sample.md 若使用記事本開啟的話:
# Title H1
## Subtitle H2
### Subtitle H3
#### Subtitle H4
##### Subtitle H5
###### Subtitle H6
**Bold Text**
*Italic Text*
~~Strikethrough~~
`Inline code`
[Link text](https://example.com)

> Blockquote
- Unordered list item 1
- Unordered list item 2
- Nested unordered item
* Another bullet
1. Ordered list item 1
2. Ordered list item 2
1. Nested ordered item
---
Horizontal rule above
```python
# Code block
print("Hello, world!")
sample.md 若使用cursor開啟的話:

3. Python 解析程式
將以下程式存成 md2json.py
(或其他你喜歡的名字):
import mistune
import os
import json
dir_py = os.path.dirname(os.path.abspath(__file__))
dir_ex = os.path.join(dir_py, 'export')
os.makedirs(dir_ex, exist_ok=True)
basename_md = 'sample.md'
path_ex = os.path.join(dir_ex, basename_md.replace('.md', '.json'))
with open(basename_md, encoding='utf-8') as f:
md_content:str = f.read()
markdown = mistune.create_markdown(renderer='ast')
#mistune.markdown.Markdown
ast:list[dict] = markdown(md_content)
with open(path_ex, 'w', encoding='utf-8') as f:
json.dump(ast, f, ensure_ascii=False, indent=4)
print(f'exported to {path_ex}' )
4. 執行程式
在命令列執行:
python md2json.py
程式會在 export
資料夾下,產生 sample.json
,裡面就是你的 Markdown AST 結構!
5. 檢視結果
打開 export/sample.json
,你會看到類似這樣的資料結構:

補充說明
- AST 結構:方便自動化分析、轉換(如產生 HTML、統計標題、內容摘要等)。
- JSON 格式:易於跨語言、跨平台應用。
- Mistune:速度快、擴充彈性高。
結論
這就是用 Python 結合 Mistune 把 Markdown 內容轉成 AST 並導出 JSON 的完整流程!
你可以進一步自訂 AST 處理、分析內容、轉換成各種格式,應用無限大!
## 參考資源
– [Mistune 官方文檔](https://mistune.lepture.com/)
– [Rich 官方文檔](https://rich.readthedocs.io/)
– [Markdown語法指南](https://www.markdownguide.org/)
推薦hahow線上學習python: https://igrape.net/30afN
近期留言