thombashi / pytablewriter

pytablewriter is a Python library to write a table in various formats: AsciiDoc / CSV / Elasticsearch / HTML / JavaScript / JSON / LaTeX / LDJSON / LTSV / Markdown / MediaWiki / NumPy / Excel / Pandas / Python / reStructuredText / SQLite / TOML / TSV.
https://pytablewriter.rtfd.io/
MIT License
610 stars 43 forks source link

Write output as rst field lists? #17

Closed iruletheworld closed 4 years ago

iruletheworld commented 5 years ago

This is a very good module and it solves a lot of my documentation problems.

I am just wondering, if a I want to turn a JSON into restructuredtext field lists, is it currently do able?

The reason is, for documentation, if it is an HTML, I usually show the JSON with a CSV table (converted from the JSON) to show more info for the user; for PDF (outputed using sphinx with Latex), I've found that rst field lists actually are rendered better than CSV tables (since they can be very long tables).

I will show what I mean.

I basically want to convert this:

into this:

How do I do this?

thombashi commented 4 years ago

Thank you for your feedback.

You can convert from JSON to restructuredtext table (rst-grid, rst-csv, rst-simple) format using pytablereader (also latex table):

import sys

import pytablereader as ptr
import pytablewriter as ptw

def main():
    j = """
    {
        "bool_del_temp": true,
        "bool_drop_brn_length": true,
        "bool_drop_id": true
    }
    """
    loader = ptr.JsonTableTextLoader(j)

    for table_data in loader.load():
        for format_name in ("rst_grid", "rst_csv", "rst_simple", "latex_table"):
            print(ptw.dumps_tabledata(table_data, format_name=format_name))
    return 0

if __name__ == '__main__':
    sys.exit(main())

Output:

.. table:: json1

    +--------------------+-----+
    |        key         |value|
    +====================+=====+
    |bool_del_temp       |True |
    +--------------------+-----+
    |bool_drop_brn_length|True |
    +--------------------+-----+
    |bool_drop_id        |True |
    +--------------------+-----+

.. csv-table:: json1
    :header: "key", "value"
    :widths: 22, 7

    "bool_del_temp", True
    "bool_drop_brn_length", True
    "bool_drop_id", True

.. table:: json1

    ====================  =====
            key           value
    ====================  =====
    bool_del_temp         True
    bool_drop_brn_length  True
    bool_drop_id          True
    ====================  =====

\begin{array}{l | l} \hline
    \verb|        key         | & \verb|value| \\ \hline
    \hline
    bool_del_temp        & True  \\ \hline
    bool_drop_brn_length & True  \\ \hline
    bool_drop_id         & True  \\ \hline
\end{array}

However, these formats may differ from your expectations. I'm not familiar with the format you describe above.