【问题标题】:How to read JSON/XML/YAML data into Sphinx RST file to programmatically generate a documentation page?如何将 JSON/XML/YAML 数据读入 Sphinx RST 文件以编程方式生成文档页面?
【发布时间】:2021-12-06 20:09:30
【问题描述】:

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

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] ]]

【问题讨论】:

  • doctest 会做你想做的事吗?

标签: python json python-sphinx restructuredtext


【解决方案1】:

您可以创建一个 Sphinx extension(例如 dhellmann 的 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') + '\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 内容发生更改,则触发脚本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-10
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多