or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-json2html

Python wrapper to convert JSON into a human readable HTML Table representation

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/json2html@1.3.x

To install, run

npx @tessl/cli install tessl/pypi-json2html@1.3.0

index.mddocs/

json2html

A Python library that converts JSON data into human-readable HTML table representations. The library provides a clean API for transforming structured JSON data into HTML tables with features like automatic array clubbing, custom table attributes, HTML escaping for security, and support for nested data structures.

Package Information

  • Package Name: json2html
  • Package Type: pypi
  • Language: Python
  • Installation: pip install json2html
  • Version: 1.3.0
  • License: MIT
  • Requirements: Python 2.7+ or Python 3.x
  • Auto-Dependencies: simplejson and ordereddict for Python < 2.7 (installed automatically)

Core Imports

Standard import for accessing all functionality:

from json2html import *

Specific import for the main converter instance:

from json2html import json2html

Import the class for manual instantiation:

from json2html import Json2Html

All imports provide access to the same functionality - the module exports both the class and a pre-instantiated json2html object.

Basic Usage

from json2html import json2html

# Simple object conversion
data = {
    "name": "json2html",
    "description": "Converts JSON to HTML tabular representation"
}
html_output = json2html.convert(json=data)
print(html_output)
# Output: <table border="1"><tr><th>name</th><td>json2html</td></tr><tr><th>description</th><td>Converts JSON to HTML tabular representation</td></tr></table>

# Array of objects with automatic clubbing
data = {
    "libraries": [
        {"name": "json2html", "language": "Python", "type": "converter"},
        {"name": "requests", "language": "Python", "type": "http"}
    ]
}
html_output = json2html.convert(json=data)
print(html_output)

Capabilities

JSON to HTML Conversion

The core functionality converts JSON data structures into HTML table format with support for objects, arrays, primitive values, and nested structures.

def convert(json="", table_attributes='border="1"', clubbing=True, encode=False, escape=True):
    """
    Convert JSON to HTML Table format.
    
    Parameters:
    - json (str|dict|list, default=""): JSON input as string, dict, or list
    - table_attributes (str, default='border="1"'): HTML table attributes (id, class, data-*)
    - clubbing (bool, default=True): Enable clubbing of array-of-objects with same keys
    - encode (bool, default=False): ASCII encode output with XML character references
    - escape (bool, default=True): HTML escape text nodes for XSS protection
    
    Returns:
    str|bytes: HTML table representation of the JSON data (bytes if encode=True)
    
    Raises:
    ValueError: If json string is malformed JSON and contains property name errors
    """

Usage examples:

from json2html import json2html

# Basic conversion
result = json2html.convert(json={"key": "value"})

# Custom table attributes
result = json2html.convert(
    json=data,
    table_attributes='class="table table-bordered table-hover" id="my-table"'
)

# Disable clubbing for arrays
result = json2html.convert(json=data, clubbing=False)

# Enable encoding for browser compatibility
result = json2html.convert(json=data, encode=True)

# Disable HTML escaping (use with caution)
result = json2html.convert(json=data, escape=False)

JSON Data Type Handling

Internal methods handle different JSON data types and convert them appropriately to HTML representations.

def convert_json_node(json_input):
    """
    Dispatch JSON input according to the outermost type and process it.
    
    Parameters:
    - json_input (any): JSON node to convert
    
    Returns:
    str: HTML representation of the JSON node
    """

def convert_list(list_input):
    """
    Convert JSON list to HTML table (with clubbing) or HTML list.
    
    Parameters:
    - list_input (list): List/array to convert
    
    Returns:
    str: HTML table or list representation
    """

def convert_object(json_input):
    """
    Convert JSON object to HTML table format.
    
    Parameters:
    - json_input (dict): Dictionary/object to convert
    
    Returns:
    str: HTML table representation
    """

Array Clubbing Analysis

The library can analyze arrays of objects to determine if they have consistent keys for table-style representation.

def column_headers_from_list_of_dicts(json_input):
    """
    Extract column headers for clubbing feature from list of dicts.
    
    Parameters:
    - json_input (list): List of dictionaries to analyze
    
    Returns:
    list|None: Column headers if uniform structure, None otherwise
    """

Class-Based API

For advanced usage, you can instantiate the Json2Html class directly:

class Json2Html:
    """
    Main converter class for JSON to HTML table transformation.
    """
    
    def convert(self, json="", table_attributes='border="1"', clubbing=True, encode=False, escape=True):
        """Convert JSON to HTML Table format - same interface as module-level function."""
    
    def convert_json_node(self, json_input):
        """Dispatch JSON input by type and convert to HTML."""
    
    def convert_list(self, list_input):
        """Convert JSON list to HTML table or list representation."""
    
    def convert_object(self, json_input):
        """Convert JSON object to HTML table format."""
    
    def column_headers_from_list_of_dicts(self, json_input):
        """Extract column headers for clubbing feature."""

Usage:

from json2html import Json2Html

converter = Json2Html()
result = converter.convert(json=data)

Module-Level Instance

The package provides a pre-instantiated converter for convenient access:

json2html = Json2Html()

This is the primary interface for most use cases:

from json2html import json2html
result = json2html.convert(json=data)

Key Features

Array Clubbing

When an array contains objects with identical keys, the library automatically creates a single table with column headers instead of separate tables for each object:

# Input with consistent object structure
data = {
    "users": [
        {"name": "Alice", "age": 30, "role": "admin"},
        {"name": "Bob", "age": 25, "role": "user"}
    ]
}

# Creates a single table with headers: name, age, role
html = json2html.convert(json=data)

Custom Table Attributes

Support for HTML table attributes including CSS classes, IDs, and data attributes:

html = json2html.convert(
    json=data,
    table_attributes='class="my-class" id="data-table" data-sortable="true"'
)

Security Features

Built-in HTML escaping prevents XSS attacks when processing untrusted JSON data:

# Safe by default - HTML tags are escaped
unsafe_data = {"content": "<script>alert('xss')</script>"}
safe_html = json2html.convert(json=unsafe_data)  # escape=True by default

Browser Compatibility

Optional ASCII encoding with XML character references for maximum browser compatibility:

html = json2html.convert(json=data, encode=True)

Python 2/3 Compatibility

The library handles Python version differences transparently, supporting both Python 2.7+ and Python 3.x environments.

Implementation Details

Type Handling

The library automatically handles different data types and Python version differences:

# Python version-specific imports and types
text_types = (str,)  # Python 3
text_types = (unicode, str)  # Python 2

JSON String Processing

When processing JSON strings, the library:

  • Attempts to parse as JSON using json.loads() with OrderedDict for consistent key ordering
  • Falls back to treating as plain text if parsing fails (except for specific property name errors)
  • Supports both unicode and byte strings as input

Error Handling

The library raises ValueError when:

  • JSON string contains malformed JSON with property name errors (e.g., "Expecting property name")
  • Other JSON parsing errors are handled gracefully by treating input as plain text

HTML Output

  • Default: Returns UTF-8 string
  • With encode=True: Returns ASCII-encoded bytes with XML character references
  • With escape=False: Raw HTML without escaping (use with trusted data only)

Special Input Handling

The library gracefully handles various edge cases:

# Empty inputs return empty string
json2html.convert(json="")      # Returns ""
json2html.convert(json=[])      # Returns ""
json2html.convert(json={})      # Returns ""

# Boolean values
json2html.convert(json=True)    # Returns "True"
json2html.convert(json=False)   # Returns "False"

# None values
json2html.convert(json=None)    # Returns ""

# XSS protection by default
json2html.convert(json="<script></script>")  # Returns "&lt;script&gt;&lt;/script&gt;"

Duck Typing Support

The library supports duck-typed objects that behave like dicts or lists:

# Objects with items(), keys(), __getitem__ methods work as dictionaries
# Objects with __iter__, __getitem__ methods work as lists
# Objects without these methods are converted to string representation

Positional Arguments

The convert method supports both keyword and positional arguments:

# Keyword argument (recommended)
json2html.convert(json=data)

# Positional argument  
json2html.convert(data)