0
# json2html
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: json2html
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install json2html`
10
- **Version**: 1.3.0
11
- **License**: MIT
12
- **Requirements**: Python 2.7+ or Python 3.x
13
- **Auto-Dependencies**: `simplejson` and `ordereddict` for Python < 2.7 (installed automatically)
14
15
## Core Imports
16
17
Standard import for accessing all functionality:
18
19
```python
20
from json2html import *
21
```
22
23
Specific import for the main converter instance:
24
25
```python
26
from json2html import json2html
27
```
28
29
Import the class for manual instantiation:
30
31
```python
32
from json2html import Json2Html
33
```
34
35
All imports provide access to the same functionality - the module exports both the class and a pre-instantiated `json2html` object.
36
37
## Basic Usage
38
39
```python
40
from json2html import json2html
41
42
# Simple object conversion
43
data = {
44
"name": "json2html",
45
"description": "Converts JSON to HTML tabular representation"
46
}
47
html_output = json2html.convert(json=data)
48
print(html_output)
49
# 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>
50
51
# Array of objects with automatic clubbing
52
data = {
53
"libraries": [
54
{"name": "json2html", "language": "Python", "type": "converter"},
55
{"name": "requests", "language": "Python", "type": "http"}
56
]
57
}
58
html_output = json2html.convert(json=data)
59
print(html_output)
60
```
61
62
## Capabilities
63
64
### JSON to HTML Conversion
65
66
The core functionality converts JSON data structures into HTML table format with support for objects, arrays, primitive values, and nested structures.
67
68
```python { .api }
69
def convert(json="", table_attributes='border="1"', clubbing=True, encode=False, escape=True):
70
"""
71
Convert JSON to HTML Table format.
72
73
Parameters:
74
- json (str|dict|list, default=""): JSON input as string, dict, or list
75
- table_attributes (str, default='border="1"'): HTML table attributes (id, class, data-*)
76
- clubbing (bool, default=True): Enable clubbing of array-of-objects with same keys
77
- encode (bool, default=False): ASCII encode output with XML character references
78
- escape (bool, default=True): HTML escape text nodes for XSS protection
79
80
Returns:
81
str|bytes: HTML table representation of the JSON data (bytes if encode=True)
82
83
Raises:
84
ValueError: If json string is malformed JSON and contains property name errors
85
"""
86
```
87
88
Usage examples:
89
90
```python
91
from json2html import json2html
92
93
# Basic conversion
94
result = json2html.convert(json={"key": "value"})
95
96
# Custom table attributes
97
result = json2html.convert(
98
json=data,
99
table_attributes='class="table table-bordered table-hover" id="my-table"'
100
)
101
102
# Disable clubbing for arrays
103
result = json2html.convert(json=data, clubbing=False)
104
105
# Enable encoding for browser compatibility
106
result = json2html.convert(json=data, encode=True)
107
108
# Disable HTML escaping (use with caution)
109
result = json2html.convert(json=data, escape=False)
110
```
111
112
### JSON Data Type Handling
113
114
Internal methods handle different JSON data types and convert them appropriately to HTML representations.
115
116
```python { .api }
117
def convert_json_node(json_input):
118
"""
119
Dispatch JSON input according to the outermost type and process it.
120
121
Parameters:
122
- json_input (any): JSON node to convert
123
124
Returns:
125
str: HTML representation of the JSON node
126
"""
127
128
def convert_list(list_input):
129
"""
130
Convert JSON list to HTML table (with clubbing) or HTML list.
131
132
Parameters:
133
- list_input (list): List/array to convert
134
135
Returns:
136
str: HTML table or list representation
137
"""
138
139
def convert_object(json_input):
140
"""
141
Convert JSON object to HTML table format.
142
143
Parameters:
144
- json_input (dict): Dictionary/object to convert
145
146
Returns:
147
str: HTML table representation
148
"""
149
```
150
151
### Array Clubbing Analysis
152
153
The library can analyze arrays of objects to determine if they have consistent keys for table-style representation.
154
155
```python { .api }
156
def column_headers_from_list_of_dicts(json_input):
157
"""
158
Extract column headers for clubbing feature from list of dicts.
159
160
Parameters:
161
- json_input (list): List of dictionaries to analyze
162
163
Returns:
164
list|None: Column headers if uniform structure, None otherwise
165
"""
166
```
167
168
### Class-Based API
169
170
For advanced usage, you can instantiate the Json2Html class directly:
171
172
```python { .api }
173
class Json2Html:
174
"""
175
Main converter class for JSON to HTML table transformation.
176
"""
177
178
def convert(self, json="", table_attributes='border="1"', clubbing=True, encode=False, escape=True):
179
"""Convert JSON to HTML Table format - same interface as module-level function."""
180
181
def convert_json_node(self, json_input):
182
"""Dispatch JSON input by type and convert to HTML."""
183
184
def convert_list(self, list_input):
185
"""Convert JSON list to HTML table or list representation."""
186
187
def convert_object(self, json_input):
188
"""Convert JSON object to HTML table format."""
189
190
def column_headers_from_list_of_dicts(self, json_input):
191
"""Extract column headers for clubbing feature."""
192
```
193
194
Usage:
195
196
```python
197
from json2html import Json2Html
198
199
converter = Json2Html()
200
result = converter.convert(json=data)
201
```
202
203
### Module-Level Instance
204
205
The package provides a pre-instantiated converter for convenient access:
206
207
```python { .api }
208
json2html = Json2Html()
209
```
210
211
This is the primary interface for most use cases:
212
213
```python
214
from json2html import json2html
215
result = json2html.convert(json=data)
216
```
217
218
## Key Features
219
220
### Array Clubbing
221
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:
222
223
```python
224
# Input with consistent object structure
225
data = {
226
"users": [
227
{"name": "Alice", "age": 30, "role": "admin"},
228
{"name": "Bob", "age": 25, "role": "user"}
229
]
230
}
231
232
# Creates a single table with headers: name, age, role
233
html = json2html.convert(json=data)
234
```
235
236
### Custom Table Attributes
237
Support for HTML table attributes including CSS classes, IDs, and data attributes:
238
239
```python
240
html = json2html.convert(
241
json=data,
242
table_attributes='class="my-class" id="data-table" data-sortable="true"'
243
)
244
```
245
246
### Security Features
247
Built-in HTML escaping prevents XSS attacks when processing untrusted JSON data:
248
249
```python
250
# Safe by default - HTML tags are escaped
251
unsafe_data = {"content": "<script>alert('xss')</script>"}
252
safe_html = json2html.convert(json=unsafe_data) # escape=True by default
253
```
254
255
### Browser Compatibility
256
Optional ASCII encoding with XML character references for maximum browser compatibility:
257
258
```python
259
html = json2html.convert(json=data, encode=True)
260
```
261
262
### Python 2/3 Compatibility
263
The library handles Python version differences transparently, supporting both Python 2.7+ and Python 3.x environments.
264
265
## Implementation Details
266
267
### Type Handling
268
269
The library automatically handles different data types and Python version differences:
270
271
```python { .api }
272
# Python version-specific imports and types
273
text_types = (str,) # Python 3
274
text_types = (unicode, str) # Python 2
275
```
276
277
### JSON String Processing
278
279
When processing JSON strings, the library:
280
- Attempts to parse as JSON using `json.loads()` with OrderedDict for consistent key ordering
281
- Falls back to treating as plain text if parsing fails (except for specific property name errors)
282
- Supports both unicode and byte strings as input
283
284
### Error Handling
285
286
The library raises `ValueError` when:
287
- JSON string contains malformed JSON with property name errors (e.g., `"Expecting property name"`)
288
- Other JSON parsing errors are handled gracefully by treating input as plain text
289
290
### HTML Output
291
292
- **Default**: Returns UTF-8 string
293
- **With `encode=True`**: Returns ASCII-encoded bytes with XML character references
294
- **With `escape=False`**: Raw HTML without escaping (use with trusted data only)
295
296
### Special Input Handling
297
298
The library gracefully handles various edge cases:
299
300
```python
301
# Empty inputs return empty string
302
json2html.convert(json="") # Returns ""
303
json2html.convert(json=[]) # Returns ""
304
json2html.convert(json={}) # Returns ""
305
306
# Boolean values
307
json2html.convert(json=True) # Returns "True"
308
json2html.convert(json=False) # Returns "False"
309
310
# None values
311
json2html.convert(json=None) # Returns ""
312
313
# XSS protection by default
314
json2html.convert(json="<script></script>") # Returns "<script></script>"
315
```
316
317
### Duck Typing Support
318
319
The library supports duck-typed objects that behave like dicts or lists:
320
321
```python
322
# Objects with items(), keys(), __getitem__ methods work as dictionaries
323
# Objects with __iter__, __getitem__ methods work as lists
324
# Objects without these methods are converted to string representation
325
```
326
327
### Positional Arguments
328
329
The `convert` method supports both keyword and positional arguments:
330
331
```python
332
# Keyword argument (recommended)
333
json2html.convert(json=data)
334
335
# Positional argument
336
json2html.convert(data)
337
```