[英]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.