如何将JSON/XML/YAML数据读取到Sphinx RST文件中以编程方式生成文档页面?



假设我有一个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,其中包含所有动物的toc树,然后为每个单独的动物创建一个这样的文件。

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扩展(例如dhellmann's datatemplates)…但是一个粗糙的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') + 'nnAnimal info here.n'
footer = 'n.. End of documentn'
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内容发生变化时触发脚本。

相关内容

最新更新