Skip to content

ontocast.cli.split_chunks

json_to_md(data, title='JSON Data', depth=1)

Convert nested JSON data to Markdown format.

Parameters:

Name Type Description Default
data dict | list

The JSON data (dict or list)

required
title str

Title for the top-level markdown document

'JSON Data'
depth int

Current heading depth (internal recursion parameter)

1

Returns:

Type Description
str

Markdown formatted string

Source code in ontocast/cli/split_chunks.py
def json_to_md(data: dict | list, title: str = "JSON Data", depth: int = 1) -> str:
    """
    Convert nested JSON data to Markdown format.

    Args:
        data: The JSON data (dict or list)
        title: Title for the top-level markdown document
        depth: Current heading depth (internal recursion parameter)

    Returns:
        Markdown formatted string
    """
    if not data:
        return ""

    md = []

    # Add title only at the top level
    if depth == 1 and title:
        md.append(f"# {title}\n\n")

    if isinstance(data, dict):
        # First, handle simple key-value pairs
        simple_pairs = []
        complex_items = []

        for key, value in data.items():
            if isinstance(value, (str, int, float, bool, type(None))):
                simple_pairs.append((key, value))
            else:
                complex_items.append((key, value))

        # Add simple pairs first
        for key, value in simple_pairs:
            md.append(f"**{key}**: {_format_value(value)}\n")

        if simple_pairs:
            md.append("\n")

        # Then handle complex items with headers
        for key, value in complex_items:
            header_level = depth + 1

            # Clean spacing - add extra newline before major sections
            if header_level < 3 and md and not md[-1].endswith("\n\n"):
                md.append("\n")

            md.append(f"{'#' * header_level} {key}\n")

            if isinstance(value, dict):
                if value:  # Skip empty dicts
                    md.append(json_to_md(value, title=None, depth=depth + 1))
            elif isinstance(value, list):
                md.extend(_handle_list(value, header_level, depth))

    elif isinstance(data, list):
        md.extend(_handle_list(data, depth, depth))

    return "".join(md)