Skip to main content

Mistune JSON

A JSON renderer for the Mistune Markdown parser.

Supported HTML elements

So far, the HTML elements supported by this renderer are limited to:

  • Paragraph, <p>
  • Image, <img>
  • Ordered lists, <ol>
  • Unordered lists, <ul>
  • All heading elements, <h1> through <h6>
  • Links, <a>
  • Emphasis, <em>
  • Strong, <strong>
  • Blockquote, <blockquote>
  • Line breake, <br>
  • Thematic breake, <hr>
  • Both inline and block code
  • Generic directives (as directive nodes; parsing is a plugin's job)

How to use the JSON renderer

Installation

The package is published in PyPI, so it can be installed through pip (as any other package):

pip install mistune-json

Usage

import mistune
from mistune_json import JsonRenderer

# Create a renderer instance
renderer = JsonRenderer()

# Create a Markdown parser with the JSON renderer
markdown = mistune.create_markdown(renderer=renderer)

# Parse Markdown text
result = markdown("# Hello, world!")

print(result)
# {'content': [{'type': 'h', 'content': [{'type': 'text', 'content': 'Hello, world!'}], 'level': 1}]}

Output Schema

The JSON output is a dictionary with a content key containing a list of nodes. Each node has a type field identifying its kind.

Node Types

Type Description Fields
text Plain text content (str)
p Paragraph content (Node[])
h Heading (h1-h6) content (Node[]), level (int 1-6)
code Code block (fenced) content (str), lang (str, optional)
codespan Inline code content (str)
blockquote Block quote content (Node[])
ol Ordered list content (Node[], of item), start (int, optional)
ul Unordered list content (Node[], of item)
item List item content (Node[])
a Link content (Node[]), href (str), title (str, optional)
img Image src (str), alt (str), title (str, optional)
em Emphasis (italic) content (Node[])
strong Strong (bold) content (Node[])
directive Generic directive name (str), attrs (object), content (Node[])
hr Thematic break (horizontal rule) -
br Line break -

content is a string only for text-bearing nodes (text, code, codespan); everywhere else it is a list of child nodes. Two rules hold at every depth:

  • Blank lines produce no node. Consecutive blank lines collapse.
  • A renderer method that returns a list is spliced into its parent. This is what makes block_text (the paragraph Mistune uses inside a tight list) transparent, so list items get a flat content array rather than [[...]].

Key order is not part of the contract; compare parsed JSON, not bytes.

Example

Input:

# Title

This is a paragraph with **bold** and *italic* text.

![alt text](image.png)

- Item 1
- Item 2

Output:

{
  "content": [
    {"type": "h", "content": [{"type": "text", "content": "Title"}], "level": 1},
    {"type": "p", "content": [
      {"type": "text", "content": "This is a paragraph with "},
      {"type": "strong", "content": [{"type": "text", "content": "bold"}]},
      {"type": "text", "content": " and "},
      {"type": "em", "content": [{"type": "text", "content": "italic"}]},
      {"type": "text", "content": " text."}
    ]},
    {"type": "img", "src": "image.png", "alt": "alt text"},
    {"type": "ul", "content": [
      {"type": "item", "content": [{"type": "text", "content": "Item 1"}]},
      {"type": "item", "content": [{"type": "text", "content": "Item 2"}]}
    ]}
  ]
}

Directives

A directive node is produced by a parser plugin, not by this package. The renderer only renames the token's children to content and copies options into attrs:

{"type": "directive", "name": "position", "attrs": {"from": "2021"}, "content": [...]}

A plugin must emit a token of this shape. children is always present, even when empty, and name and the options ride inside attrs because Mistune's render_token forwards nothing else:

{
    "type": "directive",
    "attrs": {"name": "position", "options": {"from": "2021"}},
    "children": [],
}

JsonRenderer.NAME is "json", so Mistune's HTML-only directive plugins (admonition, figure, include, toc) decline to register themselves against it.

Limitations

The following elements are not yet supported:

  • Tables (headers and rows)
  • Definition lists
  • Task lists

Extensibility

You can subclass JsonRenderer to customize the JSON output by overriding two hooks:

create_node(node_type, data)

Called for every node before it's returned. Override to add custom fields to nodes.

from mistune_json import JsonRenderer


class CustomRenderer(JsonRenderer):
    def create_node(self, node_type, data):
        node = super().create_node(node_type, data)
        node["source"] = "mistune-json"  # Add source to all nodes
        return node

finalize_output(output)

Called after all content is rendered. Override to transform the final output.

from mistune_json import JsonRenderer


class CustomRenderer(JsonRenderer):
    def finalize_output(self, output):
        output["meta"] = {"generated_by": "my-app"}
        return output

Full Example

import mistune
from mistune_json import JsonRenderer
from datetime import datetime


class CustomRenderer(JsonRenderer):
    def create_node(self, node_type, data):
        node = super().create_node(node_type, data)
        node["rendered_at"] = datetime.now().isoformat()
        return node

    def finalize_output(self, output):
        output["meta"] = {"version": "1.0"}
        return output


renderer = CustomRenderer()
markdown = mistune.create_markdown(renderer=renderer)
result = markdown("# Hello")

# Each node now has 'rendered_at', and output has 'meta'
print(result)

Contributing and Feedback

Contributions are welcome! Feel free to open issues for:

  • Enhancements - Request new features or supported elements
  • Bugs - Report problems with the JSON output structure

Repository: https://github.com/fernandonino/mistune-json

Metadata

Release files for mistune-json 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mistune-json 0.3.0
File Size Uploaded Provenance Actions
mistune_json-0.3.0.tar.gz 24.3 kB Without provenance Details for mistune_json-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mistune-json 0.3.0
File Interpreter ABI Platform Actions
mistune_json-0.3.0-py3-none-any.whl Python 3 none any Details for mistune_json-0.3.0-py3-none-any.whl

Total release size: 30.7 kB

Release files / mistune_json-0.3.0.tar.gz

Download URL mistune_json-0.3.0.tar.gz
Size 24.3 kB
Tags Source
SHA-256 checksum
How to use checksums
0cb5d598e1b63672bcd86e9857114ba74806a5d3bf6d591c981597b7e0d079db
BLAKE2b-256 checksum
How to use checksums
df657dcaad7fcec1360e57159f80928f13a996059c4444f8a04d2077c2530113
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Omarchy","version":"4.0.6","id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / mistune_json-0.3.0-py3-none-any.whl

Download URL mistune_json-0.3.0-py3-none-any.whl
Size 6.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b76d4d7ae87dbf9d4386ce6832405810a2fc1a551a8a285866040d50b0d1934d
BLAKE2b-256 checksum
How to use checksums
66d1c84e665e5651caebf0fc8c1b53c4e22779b41bdc0f114684b9055e938ccd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Omarchy","version":"4.0.6","id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for mistune-json 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page