all2md.renderers.json

JSON rendering from AST.

This module provides the JsonRenderer class which extracts structured data from AST documents and converts it to JSON format. The primary use case is extracting tables from markdown documentation as JSON arrays.

Examples

Extract tables from markdown:

Input markdown:

# Users
| name | age | active |
|------|-----|--------|
| Alice | 30 | true |
| Bob | 25 | false |

Output JSON:

{
  "Users": [
    {"name": "Alice", "age": 30, "active": true},
    {"name": "Bob", "age": 25, "active": false}
  ]
}
class all2md.renderers.json.JsonRenderer

Bases: BaseRenderer

Render AST to JSON format by extracting structured data.

This renderer extracts tables and lists from AST documents and converts them to JSON structures. Tables become arrays of objects, with column headers as keys. Preceding headings are used as structure keys.

Parameters:

options (JsonRendererOptions or None, default = None) – JSON rendering options

Examples

Basic usage (extract tables):

>>> from all2md.ast import Document, Table, TableRow, TableCell, Text, Heading
>>> from all2md.renderers.json import JsonRenderer
>>> table = Table(
...     header=TableRow(cells=[
...         TableCell(content=[Text(content="name")]),
...         TableCell(content=[Text(content="value")])
...     ]),
...     rows=[
...         TableRow(cells=[
...             TableCell(content=[Text(content="timeout")]),
...             TableCell(content=[Text(content="30")])
...         ])
...     ]
... )
>>> heading = Heading(level=1, content=[Text(content="Configuration")])
>>> doc = Document(children=[heading, table])
>>> renderer = JsonRenderer()
>>> json_text = renderer.render_to_string(doc)

Extract lists as arrays:

>>> from all2md.options.json import JsonRendererOptions
>>> options = JsonRendererOptions(extract_mode="both")
>>> renderer = JsonRenderer(options)

Initialize the JSON renderer with options.

__init__(options: JsonRendererOptions | None = None)

Initialize the JSON renderer with options.

render(doc: Document, output: str | Path | IO[bytes] | IO[str]) None

Render AST document to JSON file.

Parameters:
  • doc (Document) – AST Document node to render

  • output (str, Path, IO[bytes], or IO[str]) – Output destination

render_to_string(doc: Document) str

Render AST document to JSON string.

Parameters:

doc (Document) – AST Document node to render

Returns:

JSON string

Return type:

str

class all2md.renderers.json.DataExtractor

Bases: object

Extractor that walks AST and extracts structured data.

This class walks the AST and extracts tables and lists into structured data according to the renderer options.

Parameters:

options (JsonRendererOptions) – Rendering options

Initialize the data extractor.

__init__(options: JsonRendererOptions)

Initialize the data extractor.

extract(doc: Document) dict[str, Any]

Extract data from document.

Parameters:

doc (Document) – Document to extract from

Returns:

Extracted data

Return type:

dict