[英]How to read JSON/XML/YAML data into Sphinx RST file to programmatically generate a documentation page?
假設我有一個 JSON/YAML/XML 等動物園動物,我想為動物園中的所有動物制作一些文檔。 所以我有一個像這樣的 JSON:
{
"zooName": "C town's Zoo",
"animals": [
"tiger": {
"species":"some_species_name_here",
"weight": 120
},
"bear":{
"species":"some_other_species_name",
"weight": 100
}
]
}
在另一個 SSG 中,我可以做類似的事情
> Bring in a JSON file from /data/myfile.json
> Access some index of that file like [animals][tiger], etc...
> Show that data as a part of the HTML template that is made by, say, `tiger.rst`
我將如何在 Sphinx 中實現這一點? 假設我有一個animals.rst
,里面有我所有動物的目錄樹,然后每個animals.rst
都有一個這樣的文件。
Tiger
=======================================
Tiger info here.
Species:
[[ Access my json here and show content from jsonfile[animals][tiger][species] ]]
Weight:
[[ Access my json here and show content from jsonfile[animals][tiger][weight] ]]
你可以創建一個Sphinx 擴展......但是一個粗略的update.py
預處理腳本可能會做:
#!/usr/bin/env python
"""To launch: ``$ python update.py > animals.rst`` """
import json
def headline(text, adorn='='):
return text + '\n' + adorn*len(text)
def main():
header = headline('Animals') + '\n\nAnimal info here.\n'
footer = '\n.. End of document\n'
mask = '* {name} -- {species}'
with open('animals.json', 'r') as infile:
data = json.load(infile)
print(header)
for beast in data['animals']:
print(mask.format(**beast))
print(footer)
if __name__ == '__main__':
main()
對於任何更高級的布局,從 Python 字符串format
升級到Jinja2模板。
animals.json
與您的示例略有不同:
{
"zooName": "C town's Zoo",
"animals": [
{"name": "tiger", "species": "some_species_name_here", "weight": 120},
{"name": "bear", "species": "some_other_species_name", "weight": 100}
]
}
最后,向 Sphinx Makefile添加一條規則,如果 JSON 內容發生更改,則觸發腳本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.