codeblock that can switch contents between YAML and JSON format

28 views
Skip to first unread message

Shane Gibson

unread,
Jul 28, 2021, 11:35:17 AM7/28/21
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.

Thanks!
~~shane


Darren Ng

unread,
Jul 29, 2021, 9:07:40 PM7/29/21
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:
https://adamtheautomator.com/yaml-to-json
https://gist.github.com/noahcoad/46909253a5891af3699580b8f17baba8
https://stackoverflow.com/q/15941996/
https://stackoverflow.com/q/27382552/
https://stackoverflow.com/q/42342549

2021-07-30
Darren Ng
 
Reply all
Reply to author
Forward
0 new messages