Python wrapper to convert JSON into a human readable HTML Table representation
npx @tessl/cli install tessl/pypi-json2html@1.3.0A 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.
pip install json2htmlsimplejson and ordereddict for Python < 2.7 (installed automatically)Standard import for accessing all functionality:
from json2html import *Specific import for the main converter instance:
from json2html import json2htmlImport the class for manual instantiation:
from json2html import Json2HtmlAll imports provide access to the same functionality - the module exports both the class and a pre-instantiated json2html object.
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)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)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
"""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
"""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)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)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)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"'
)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 defaultOptional ASCII encoding with XML character references for maximum browser compatibility:
html = json2html.convert(json=data, encode=True)The library handles Python version differences transparently, supporting both Python 2.7+ and Python 3.x environments.
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 2When processing JSON strings, the library:
json.loads() with OrderedDict for consistent key orderingThe library raises ValueError when:
"Expecting property name")encode=True: Returns ASCII-encoded bytes with XML character referencesescape=False: Raw HTML without escaping (use with trusted data only)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 "<script></script>"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 representationThe convert method supports both keyword and positional arguments:
# Keyword argument (recommended)
json2html.convert(json=data)
# Positional argument
json2html.convert(data)