codeblock that can switch contents between YAML and JSON format

Skip to first unread message

Shane Gibson

Jul 28, 2021, 11:35:17 AMJul 28
to sphinx-users
Hi All,

Relative newbie to configuring/tweaking Sphinx, but have been using RST/Sphinx heavily for a few years.  Spent a good while trying to search for this, but as you may expect "yaml" and "json" are busy keywords...  

We document our API and platform operations with lots of example.  Our system flexibly uses both YAML and JSON format.  So we often use codeblocks like:

.. code-block:: json

  { "stuff": true }

.. code-block:: yaml

  stuff: true

Which is a pain in the behind to generate the example twice, and makes for a maintenance headache on updates, etc.  

Is there any way (plugin, etc) to create a codeblock in Sphinx that is either expressed in YAML or JSON, but can "switch" output views by re-rendering it to the other format?

If I have missed a similar post or information - I'm happy to be pointed at the right example/documentation for reference.


Darren Ng

Jul 29, 2021, 9:07:40 PMJul 29
to sphinx-users
Hi shane,

Dirty Unix pornographic method, ugly but likely to work :)

(command not tested, might be some typo there)

(MM) ::= Manual step that you perform
(--) ::= Automatic steps that you put in da Makefile

  (1) (MM) Write the example in either demo.json or demo.yaml

  (2) (--) Convert demo.json->demo.yaml or demo.yaml->demo.json [*]

  (3) (--) (Indent all lines with 4 spaces)
           sh -c "sed -i 's/^/    /' demo.json
           sh -c "sed -i 's/^/    /' demo.yaml
  (4) (--) (Prepend)
           cat <(echo '.. code-block:: json') demo.json > json.rst
           cat <(echo '.. code-block:: yaml') demo.yaml > yaml.rst

  (5) (--) Add ".. include:: json.txt"
           and ".. include:: yaml.txt"
           to wherever appropriate in your reStructuredText document

[*]: A quick & drity Google search gives these examples:

Darren Ng
Reply all
Reply to author
0 new messages