json-structure-summary 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- json_structure_summary/__init__.py +10 -0
- json_structure_summary/core.py +376 -0
- json_structure_summary-0.1.0.dist-info/METADATA +230 -0
- json_structure_summary-0.1.0.dist-info/RECORD +8 -0
- json_structure_summary-0.1.0.dist-info/WHEEL +5 -0
- json_structure_summary-0.1.0.dist-info/entry_points.txt +2 -0
- json_structure_summary-0.1.0.dist-info/licenses/LICENSE.md +21 -0
- json_structure_summary-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
json-structure-summary.py - Infer and summarize the structure of a JSON file.
|
|
4
|
+
|
|
5
|
+
Can be used as a CLI tool or imported as a module.
|
|
6
|
+
|
|
7
|
+
CLI Usage:
|
|
8
|
+
python json-structure-summary.py input.json [--schema | --summary] [--pretty]
|
|
9
|
+
cat input.json | python json-structure-summary.py
|
|
10
|
+
|
|
11
|
+
Module Usage:
|
|
12
|
+
from json_structure_summary import summarize_json_structure
|
|
13
|
+
result = summarize_json_structure("path/to/file.json", output_format='summary', pretty=True)
|
|
14
|
+
# or pass JSON string directly
|
|
15
|
+
result = summarize_json_structure('{"key": "value"}', from_file=False)
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import sys
|
|
19
|
+
import json
|
|
20
|
+
import argparse
|
|
21
|
+
import re
|
|
22
|
+
from collections import defaultdict, Counter
|
|
23
|
+
from typing import Any, Dict, List, Union, Optional, Tuple, Literal
|
|
24
|
+
|
|
25
|
+
# ----------------------------------------------------------------------
|
|
26
|
+
# JSON repair (handles common malformations)
|
|
27
|
+
# ----------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
def remove_json_comments(text: str) -> str:
|
|
30
|
+
"""Remove C-style comments (// and /* */) from JSON text."""
|
|
31
|
+
# Remove multi-line comments
|
|
32
|
+
text = re.sub(r'/\*.*?\*/', '', text, flags=re.DOTALL)
|
|
33
|
+
# Remove single-line comments
|
|
34
|
+
text = re.sub(r'//.*?$', '', text, flags=re.MULTILINE)
|
|
35
|
+
return text
|
|
36
|
+
|
|
37
|
+
def remove_trailing_commas(text: str) -> str:
|
|
38
|
+
"""Remove trailing commas in objects and arrays."""
|
|
39
|
+
# Object: remove comma before }
|
|
40
|
+
text = re.sub(r',\s*}', '}', text)
|
|
41
|
+
# Array: remove comma before ]
|
|
42
|
+
text = re.sub(r',\s*]', ']', text)
|
|
43
|
+
return text
|
|
44
|
+
|
|
45
|
+
def repair_json(text: str) -> str:
|
|
46
|
+
"""Apply a series of repairs to try to make invalid JSON valid."""
|
|
47
|
+
# Remove BOM if present
|
|
48
|
+
if text.startswith('\ufeff'):
|
|
49
|
+
text = text[1:]
|
|
50
|
+
# Remove comments
|
|
51
|
+
text = remove_json_comments(text)
|
|
52
|
+
# Remove trailing commas
|
|
53
|
+
text = remove_trailing_commas(text)
|
|
54
|
+
return text
|
|
55
|
+
|
|
56
|
+
def parse_json_safe(content: str) -> Any:
|
|
57
|
+
"""Attempt to parse JSON, first with strict, then with repairs."""
|
|
58
|
+
try:
|
|
59
|
+
return json.loads(content)
|
|
60
|
+
except json.JSONDecodeError:
|
|
61
|
+
# Try with strict=False (allows control characters)
|
|
62
|
+
try:
|
|
63
|
+
return json.loads(content, strict=False)
|
|
64
|
+
except json.JSONDecodeError:
|
|
65
|
+
# Repair and retry
|
|
66
|
+
repaired = repair_json(content)
|
|
67
|
+
try:
|
|
68
|
+
return json.loads(repaired)
|
|
69
|
+
except json.JSONDecodeError as e:
|
|
70
|
+
# Re-raise with original content for better error context
|
|
71
|
+
raise json.JSONDecodeError(
|
|
72
|
+
f"Unable to parse JSON even after repair: {e.msg}",
|
|
73
|
+
content,
|
|
74
|
+
e.pos
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
# ----------------------------------------------------------------------
|
|
78
|
+
# Structure inference
|
|
79
|
+
# ----------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
class StructureInferrer:
|
|
82
|
+
"""Infer structural schema from JSON data."""
|
|
83
|
+
|
|
84
|
+
def __init__(self, max_samples: Optional[int] = None):
|
|
85
|
+
self.max_samples = max_samples
|
|
86
|
+
|
|
87
|
+
def infer(self, data: Any) -> Dict:
|
|
88
|
+
"""Recursively infer schema from data."""
|
|
89
|
+
return self._infer_value(data, path='$')
|
|
90
|
+
|
|
91
|
+
def _infer_value(self, value: Any, path: str) -> Dict:
|
|
92
|
+
"""Return a schema dictionary for a single value."""
|
|
93
|
+
if value is None:
|
|
94
|
+
return {'type': 'null'}
|
|
95
|
+
if isinstance(value, bool):
|
|
96
|
+
return {'type': 'boolean'}
|
|
97
|
+
if isinstance(value, int):
|
|
98
|
+
return {'type': 'integer'}
|
|
99
|
+
if isinstance(value, float):
|
|
100
|
+
return {'type': 'number'}
|
|
101
|
+
if isinstance(value, str):
|
|
102
|
+
return {'type': 'string'}
|
|
103
|
+
if isinstance(value, list):
|
|
104
|
+
return self._infer_array(value, path)
|
|
105
|
+
if isinstance(value, dict):
|
|
106
|
+
return self._infer_object(value, path)
|
|
107
|
+
# Should not happen
|
|
108
|
+
return {'type': 'unknown'}
|
|
109
|
+
|
|
110
|
+
def _infer_object(self, obj: Dict, path: str) -> Dict:
|
|
111
|
+
"""Infer schema for an object (dict)."""
|
|
112
|
+
schema = {'type': 'object', 'properties': {}, 'required': []}
|
|
113
|
+
for key, val in obj.items():
|
|
114
|
+
prop_path = f"{path}.{key}"
|
|
115
|
+
prop_schema = self._infer_value(val, prop_path)
|
|
116
|
+
schema['properties'][key] = prop_schema
|
|
117
|
+
# Mark as required (since we are inferring from a single sample)
|
|
118
|
+
schema['required'].append(key)
|
|
119
|
+
return schema
|
|
120
|
+
|
|
121
|
+
def _infer_array(self, arr: List, path: str) -> Dict:
|
|
122
|
+
"""Infer schema for an array by inspecting elements."""
|
|
123
|
+
if not arr:
|
|
124
|
+
# Empty array: type array with no items specified
|
|
125
|
+
return {'type': 'array'}
|
|
126
|
+
|
|
127
|
+
# Limit samples if requested
|
|
128
|
+
samples = arr if self.max_samples is None else arr[:self.max_samples]
|
|
129
|
+
|
|
130
|
+
# Collect schemas for each element
|
|
131
|
+
item_schemas = []
|
|
132
|
+
for idx, item in enumerate(samples):
|
|
133
|
+
item_path = f"{path}[{idx}]"
|
|
134
|
+
item_schemas.append(self._infer_value(item, item_path))
|
|
135
|
+
|
|
136
|
+
# Combine schemas: if all same, use that; else use anyOf/oneOf
|
|
137
|
+
merged = self._merge_schemas(item_schemas)
|
|
138
|
+
return {'type': 'array', 'items': merged}
|
|
139
|
+
|
|
140
|
+
def _merge_schemas(self, schemas: List[Dict]) -> Dict:
|
|
141
|
+
"""Merge multiple schemas into one (union)."""
|
|
142
|
+
if len(schemas) == 1:
|
|
143
|
+
return schemas[0]
|
|
144
|
+
|
|
145
|
+
# Simplify: if all have same type, combine their sub-structures
|
|
146
|
+
types = [s.get('type') for s in schemas]
|
|
147
|
+
if all(t == types[0] for t in types):
|
|
148
|
+
# Same type, merge properties/items if applicable
|
|
149
|
+
return self._merge_same_type(schemas, types[0])
|
|
150
|
+
else:
|
|
151
|
+
# Different types -> use anyOf
|
|
152
|
+
return {'anyOf': schemas}
|
|
153
|
+
|
|
154
|
+
def _merge_same_type(self, schemas: List[Dict], typ: str) -> Dict:
|
|
155
|
+
"""Merge schemas that all have the same type."""
|
|
156
|
+
if typ == 'object':
|
|
157
|
+
# Combine properties and required fields
|
|
158
|
+
merged = {'type': 'object', 'properties': {}, 'required': []}
|
|
159
|
+
# Collect all keys and schemas for merging
|
|
160
|
+
all_keys = set()
|
|
161
|
+
for s in schemas:
|
|
162
|
+
all_keys.update(s.get('properties', {}).keys())
|
|
163
|
+
for key in all_keys:
|
|
164
|
+
# Gather schemas for this key from all objects
|
|
165
|
+
key_schemas = []
|
|
166
|
+
for s in schemas:
|
|
167
|
+
if key in s.get('properties', {}):
|
|
168
|
+
key_schemas.append(s['properties'][key])
|
|
169
|
+
if key_schemas:
|
|
170
|
+
merged['properties'][key] = self._merge_schemas(key_schemas)
|
|
171
|
+
# Required: keys that appear in all objects
|
|
172
|
+
required_sets = [set(s.get('properties', {}).keys()) for s in schemas]
|
|
173
|
+
common_keys = set.intersection(*required_sets) if required_sets else set()
|
|
174
|
+
merged['required'] = list(common_keys)
|
|
175
|
+
# Remove empty required
|
|
176
|
+
if not merged['required']:
|
|
177
|
+
del merged['required']
|
|
178
|
+
return merged
|
|
179
|
+
|
|
180
|
+
elif typ == 'array':
|
|
181
|
+
# Merge items schemas
|
|
182
|
+
items_schemas = [s.get('items', {'type': 'any'}) for s in schemas]
|
|
183
|
+
merged_items = self._merge_schemas(items_schemas)
|
|
184
|
+
return {'type': 'array', 'items': merged_items}
|
|
185
|
+
|
|
186
|
+
else:
|
|
187
|
+
# Primitive types: they are identical (same type), so just return one.
|
|
188
|
+
return schemas[0]
|
|
189
|
+
|
|
190
|
+
# ----------------------------------------------------------------------
|
|
191
|
+
# Statistics collection (optional)
|
|
192
|
+
# ----------------------------------------------------------------------
|
|
193
|
+
|
|
194
|
+
class StructureStats:
|
|
195
|
+
"""Collect statistics about the data (e.g., count of types, field presence)."""
|
|
196
|
+
def __init__(self):
|
|
197
|
+
self.type_counts = Counter()
|
|
198
|
+
self.field_presence = defaultdict(int) # path -> count
|
|
199
|
+
self.array_lengths = defaultdict(list) # path -> list of lengths
|
|
200
|
+
|
|
201
|
+
def collect(self, data: Any, path: str = '$'):
|
|
202
|
+
self.type_counts[type(data).__name__] += 1
|
|
203
|
+
if isinstance(data, dict):
|
|
204
|
+
for k, v in data.items():
|
|
205
|
+
subpath = f"{path}.{k}"
|
|
206
|
+
self.field_presence[subpath] += 1
|
|
207
|
+
self.collect(v, subpath)
|
|
208
|
+
elif isinstance(data, list):
|
|
209
|
+
self.array_lengths[path].append(len(data))
|
|
210
|
+
for idx, item in enumerate(data):
|
|
211
|
+
self.collect(item, f"{path}[{idx}]")
|
|
212
|
+
|
|
213
|
+
# ----------------------------------------------------------------------
|
|
214
|
+
# Output formatting
|
|
215
|
+
# ----------------------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
def format_schema(schema: Dict, pretty: bool = False) -> str:
|
|
218
|
+
"""Convert schema dict to JSON string."""
|
|
219
|
+
indent = 2 if pretty else None
|
|
220
|
+
return json.dumps(schema, indent=indent, ensure_ascii=False)
|
|
221
|
+
|
|
222
|
+
def format_summary(schema: Dict, stats: Optional[StructureStats] = None) -> str:
|
|
223
|
+
"""Produce a human-readable structural summary."""
|
|
224
|
+
lines = []
|
|
225
|
+
def walk(schema, indent=0):
|
|
226
|
+
prefix = " " * indent
|
|
227
|
+
typ = schema.get('type', 'unknown')
|
|
228
|
+
if typ == 'object':
|
|
229
|
+
lines.append(f"{prefix}Object:")
|
|
230
|
+
for k, v in schema.get('properties', {}).items():
|
|
231
|
+
required = k in schema.get('required', [])
|
|
232
|
+
req_marker = " (required)" if required else ""
|
|
233
|
+
lines.append(f"{prefix} {k}{req_marker}:")
|
|
234
|
+
walk(v, indent + 2)
|
|
235
|
+
elif typ == 'array':
|
|
236
|
+
items = schema.get('items')
|
|
237
|
+
if items:
|
|
238
|
+
lines.append(f"{prefix}Array of:")
|
|
239
|
+
walk(items, indent + 1)
|
|
240
|
+
else:
|
|
241
|
+
lines.append(f"{prefix}Array (empty)")
|
|
242
|
+
else:
|
|
243
|
+
lines.append(f"{prefix}{typ}")
|
|
244
|
+
walk(schema)
|
|
245
|
+
if stats:
|
|
246
|
+
lines.append("\nStatistics:")
|
|
247
|
+
for path, count in stats.field_presence.items():
|
|
248
|
+
lines.append(f" {path}: present in {count} objects")
|
|
249
|
+
for path, lengths in stats.array_lengths.items():
|
|
250
|
+
if lengths:
|
|
251
|
+
avg = sum(lengths)/len(lengths)
|
|
252
|
+
lines.append(f" {path}: lengths {min(lengths)}-{max(lengths)} (avg {avg:.1f}, {len(lengths)} entries)")
|
|
253
|
+
return "\n".join(lines)
|
|
254
|
+
|
|
255
|
+
# ----------------------------------------------------------------------
|
|
256
|
+
# Public API
|
|
257
|
+
# ----------------------------------------------------------------------
|
|
258
|
+
|
|
259
|
+
def summarize_json_structure(
|
|
260
|
+
source: str,
|
|
261
|
+
from_file: bool = True,
|
|
262
|
+
output_format: Literal['schema', 'summary'] = 'schema',
|
|
263
|
+
pretty: bool = False,
|
|
264
|
+
max_samples: Optional[int] = None,
|
|
265
|
+
return_type: Literal['str', 'dict'] = 'str'
|
|
266
|
+
) -> Union[str, Dict]:
|
|
267
|
+
"""
|
|
268
|
+
Analyze the structure of JSON data and return a schema or summary.
|
|
269
|
+
|
|
270
|
+
Parameters:
|
|
271
|
+
source (str): Either a file path (if from_file=True) or a JSON string.
|
|
272
|
+
from_file (bool): If True, source is a file path; else source is JSON content.
|
|
273
|
+
output_format (str): 'schema' for JSON Schema, 'summary' for human-readable.
|
|
274
|
+
pretty (bool): If True and output_format='schema', indent the JSON.
|
|
275
|
+
max_samples (int, optional): Maximum number of elements to sample from arrays.
|
|
276
|
+
return_type (str): 'str' to return a string, 'dict' to return the schema dict
|
|
277
|
+
(only valid for output_format='schema').
|
|
278
|
+
|
|
279
|
+
Returns:
|
|
280
|
+
Union[str, Dict]: The schema or summary as a string or dict.
|
|
281
|
+
|
|
282
|
+
Raises:
|
|
283
|
+
FileNotFoundError: If source is a file and does not exist.
|
|
284
|
+
json.JSONDecodeError: If JSON cannot be parsed after repairs.
|
|
285
|
+
ValueError: If return_type='dict' and output_format='summary'.
|
|
286
|
+
"""
|
|
287
|
+
# Read input
|
|
288
|
+
if from_file:
|
|
289
|
+
with open(source, 'r', encoding='utf-8') as f:
|
|
290
|
+
content = f.read()
|
|
291
|
+
else:
|
|
292
|
+
content = source
|
|
293
|
+
|
|
294
|
+
# Parse
|
|
295
|
+
data = parse_json_safe(content)
|
|
296
|
+
|
|
297
|
+
# Collect stats (always, to use in summary)
|
|
298
|
+
stats = StructureStats()
|
|
299
|
+
stats.collect(data)
|
|
300
|
+
|
|
301
|
+
# Infer schema
|
|
302
|
+
inferrer = StructureInferrer(max_samples=max_samples)
|
|
303
|
+
schema = inferrer.infer(data)
|
|
304
|
+
|
|
305
|
+
# Return based on format
|
|
306
|
+
if output_format == 'schema':
|
|
307
|
+
if return_type == 'dict':
|
|
308
|
+
return schema
|
|
309
|
+
else:
|
|
310
|
+
return format_schema(schema, pretty=pretty)
|
|
311
|
+
elif output_format == 'summary':
|
|
312
|
+
if return_type == 'dict':
|
|
313
|
+
raise ValueError("return_type='dict' is not supported for output_format='summary'")
|
|
314
|
+
return format_summary(schema, stats)
|
|
315
|
+
else:
|
|
316
|
+
raise ValueError(f"Invalid output_format: {output_format}")
|
|
317
|
+
|
|
318
|
+
# ----------------------------------------------------------------------
|
|
319
|
+
# CLI
|
|
320
|
+
# ----------------------------------------------------------------------
|
|
321
|
+
|
|
322
|
+
def main():
|
|
323
|
+
parser = argparse.ArgumentParser(
|
|
324
|
+
description="Summarize JSON structure (infer schema and statistics)."
|
|
325
|
+
)
|
|
326
|
+
parser.add_argument('file', nargs='?', help='JSON file to analyze (omit for stdin)')
|
|
327
|
+
parser.add_argument('--schema', action='store_true', default=True,
|
|
328
|
+
help='Output JSON Schema (default)')
|
|
329
|
+
parser.add_argument('--summary', action='store_true',
|
|
330
|
+
help='Output human-readable summary')
|
|
331
|
+
parser.add_argument('--pretty', action='store_true',
|
|
332
|
+
help='Pretty-print output')
|
|
333
|
+
parser.add_argument('--max-samples', type=int, default=None,
|
|
334
|
+
help='Max array elements to sample for inference (default: all)')
|
|
335
|
+
args = parser.parse_args()
|
|
336
|
+
|
|
337
|
+
# Determine output format
|
|
338
|
+
if args.summary:
|
|
339
|
+
output_format = 'summary'
|
|
340
|
+
else:
|
|
341
|
+
output_format = 'schema'
|
|
342
|
+
|
|
343
|
+
# Read input
|
|
344
|
+
if args.file:
|
|
345
|
+
source = args.file
|
|
346
|
+
from_file = True
|
|
347
|
+
else:
|
|
348
|
+
# Read from stdin
|
|
349
|
+
source = sys.stdin.read()
|
|
350
|
+
from_file = False
|
|
351
|
+
|
|
352
|
+
try:
|
|
353
|
+
result = summarize_json_structure(
|
|
354
|
+
source=source,
|
|
355
|
+
from_file=from_file,
|
|
356
|
+
output_format=output_format,
|
|
357
|
+
pretty=args.pretty,
|
|
358
|
+
max_samples=args.max_samples,
|
|
359
|
+
return_type='str'
|
|
360
|
+
)
|
|
361
|
+
print(result)
|
|
362
|
+
except FileNotFoundError as e:
|
|
363
|
+
print(f"Error: {e}", file=sys.stderr)
|
|
364
|
+
sys.exit(1)
|
|
365
|
+
except json.JSONDecodeError as e:
|
|
366
|
+
# Provide detailed error with line/col
|
|
367
|
+
line = source.count('\n', 0, e.pos) + 1 if from_file else 1
|
|
368
|
+
col = e.pos - source.rfind('\n', 0, e.pos) if from_file else e.pos
|
|
369
|
+
print(f"JSON decode error at line {line}, column {col}: {e.msg}", file=sys.stderr)
|
|
370
|
+
sys.exit(1)
|
|
371
|
+
except Exception as e:
|
|
372
|
+
print(f"Unexpected error: {e}", file=sys.stderr)
|
|
373
|
+
sys.exit(1)
|
|
374
|
+
|
|
375
|
+
if __name__ == '__main__':
|
|
376
|
+
main()
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: json-structure-summary
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Infer and summarize the structure of any JSON file – even malformed ones – as a schema or human-readable tree.
|
|
5
|
+
Author: Andrew Kingdom
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/akingdom/json-structure-summary
|
|
8
|
+
Project-URL: Repository, https://github.com/akingdom/json-structure-summary
|
|
9
|
+
Project-URL: Issues, https://github.com/akingdom/json-structure-summary/issues
|
|
10
|
+
Keywords: json,schema,inference,validation,structural-analysis,cli,data-exploration
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Requires-Python: >=3.7
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE.md
|
|
24
|
+
Provides-Extra: test
|
|
25
|
+
Requires-Dist: pytest>=7.0; extra == "test"
|
|
26
|
+
Requires-Dist: pytest-cov>=4.0; extra == "test"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# JSON Structure Summary
|
|
30
|
+
|
|
31
|
+
**Infer and summarise the structure of any JSON file – even malformed ones – as a JSON Schema or a human‑readable tree.**
|
|
32
|
+
|
|
33
|
+
[](https://pypi.org/project/json-structure-summary/)
|
|
34
|
+
[](https://opensource.org/licenses/MIT)
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## Why do developers need this?
|
|
39
|
+
|
|
40
|
+
Working with unknown JSON data is a common pain point:
|
|
41
|
+
|
|
42
|
+
- You receive a large JSON file and have **no idea what’s inside**.
|
|
43
|
+
- The file is **malformed** (trailing commas, C‑style comments) and breaks normal parsers.
|
|
44
|
+
- You need to **generate a JSON Schema** for validation or documentation.
|
|
45
|
+
- You want to **quickly understand the structure** without reading thousands of lines.
|
|
46
|
+
- You need **statistics** (field presence, array lengths) to assess data quality.
|
|
47
|
+
|
|
48
|
+
**json-structure-summary** solves these problems in one command. It:
|
|
49
|
+
|
|
50
|
+
- **Repairs common JSON errors** (comments, trailing commas, BOM) automatically.
|
|
51
|
+
- **Infers a JSON Schema** (draft‑07) that accurately describes the data, including union types, optional fields, and nested structures.
|
|
52
|
+
- **Provides a human‑readable summary** with field presence and array length statistics.
|
|
53
|
+
- **Works as a library** so you can integrate it into your own Python tools.
|
|
54
|
+
|
|
55
|
+
Whether you’re exploring a new API response, debugging a data pipeline, or writing documentation, this tool gives you instant insight into your JSON data.
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## Features
|
|
60
|
+
|
|
61
|
+
- **Robust parsing** – strips `//` and `/* */` comments, removes trailing commas, handles byte‑order marks.
|
|
62
|
+
- **Schema inference** – outputs a standard JSON Schema (draft‑07) that you can use with validators like `jsonschema`.
|
|
63
|
+
- **Mixed‑type support** – arrays with different element types are represented using `anyOf`.
|
|
64
|
+
- **Optionality detection** – fields are marked `required` only if they appear in *every* object across the dataset.
|
|
65
|
+
- **Human‑readable summary** – prints a tree structure with type annotations and (optionally) statistics.
|
|
66
|
+
- **Statistics** – shows field presence counts and array length ranges (min, max, average).
|
|
67
|
+
- **Performance** – limit array sampling with `--max-samples` to handle huge files quickly.
|
|
68
|
+
- **Library friendly** – import `summarize_json_structure()` and use it programmatically.
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Installation
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pip install json-structure-summary
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Or install directly from source:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
git clone https://github.com/akingdom/json-structure-summary.git
|
|
82
|
+
cd json-structure-summary
|
|
83
|
+
pip install -e .
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## Usage
|
|
89
|
+
|
|
90
|
+
### Command‑line interface
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
# Basic usage – outputs JSON Schema
|
|
94
|
+
json-structure-summary data.json
|
|
95
|
+
|
|
96
|
+
# Human‑readable summary with statistics
|
|
97
|
+
json-structure-summary data.json --summary
|
|
98
|
+
|
|
99
|
+
# Pretty‑print the schema
|
|
100
|
+
json-structure-summary data.json --schema --pretty
|
|
101
|
+
|
|
102
|
+
# Limit array sampling to 100 elements for performance
|
|
103
|
+
json-structure-summary data.json --max-samples 100
|
|
104
|
+
|
|
105
|
+
# Read from stdin
|
|
106
|
+
cat data.json | json-structure-summary
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Options
|
|
110
|
+
|
|
111
|
+
| Option | Description |
|
|
112
|
+
|--------|-------------|
|
|
113
|
+
| `--schema` | Output a JSON Schema (default) |
|
|
114
|
+
| `--summary` | Output a human‑readable structural summary |
|
|
115
|
+
| `--pretty` | Pretty‑print the output (indent 2) |
|
|
116
|
+
| `--max-samples N` | Inspect at most N elements per array (default: all) |
|
|
117
|
+
| `--help` | Show help |
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## Examples
|
|
122
|
+
|
|
123
|
+
### Input JSON (with trailing commas and comments)
|
|
124
|
+
|
|
125
|
+
```json
|
|
126
|
+
{
|
|
127
|
+
"users": [ // list of users
|
|
128
|
+
{"id": 1, "name": "Alice", "active": true,},
|
|
129
|
+
{"id": 2, "name": "Bob", "active": false, "tags": ["admin"]}
|
|
130
|
+
]
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### Output (schema, pretty‑printed)
|
|
135
|
+
|
|
136
|
+
```json
|
|
137
|
+
{
|
|
138
|
+
"type": "object",
|
|
139
|
+
"properties": {
|
|
140
|
+
"users": {
|
|
141
|
+
"type": "array",
|
|
142
|
+
"items": {
|
|
143
|
+
"type": "object",
|
|
144
|
+
"properties": {
|
|
145
|
+
"id": { "type": "integer" },
|
|
146
|
+
"name": { "type": "string" },
|
|
147
|
+
"active": { "type": "boolean" },
|
|
148
|
+
"tags": {
|
|
149
|
+
"type": "array",
|
|
150
|
+
"items": { "type": "string" }
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
"required": ["id", "name", "active"] // 'tags' is optional
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
"required": ["users"]
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### Summary output
|
|
162
|
+
|
|
163
|
+
```
|
|
164
|
+
Object:
|
|
165
|
+
users:
|
|
166
|
+
Array of:
|
|
167
|
+
Object:
|
|
168
|
+
id:
|
|
169
|
+
integer
|
|
170
|
+
name:
|
|
171
|
+
string
|
|
172
|
+
active:
|
|
173
|
+
boolean
|
|
174
|
+
tags:
|
|
175
|
+
Array of:
|
|
176
|
+
string
|
|
177
|
+
|
|
178
|
+
Statistics:
|
|
179
|
+
$.users: lengths 2-2 (avg 2.0, 1 entries)
|
|
180
|
+
$.users[0].id: present in 1 objects
|
|
181
|
+
$.users[0].name: present in 1 objects
|
|
182
|
+
...
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
---
|
|
186
|
+
|
|
187
|
+
## Using as a library
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
from json_structure_summary import summarize_json_structure
|
|
191
|
+
|
|
192
|
+
# From a file, get schema as string
|
|
193
|
+
schema_str = summarize_json_structure('data.json', pretty=True)
|
|
194
|
+
|
|
195
|
+
# From a file, get schema as dict
|
|
196
|
+
schema_dict = summarize_json_structure('data.json', return_type='dict')
|
|
197
|
+
|
|
198
|
+
# From a JSON string, get summary
|
|
199
|
+
summary = summarize_json_structure(
|
|
200
|
+
'{"x": 1, "y": "hello"}',
|
|
201
|
+
from_file=False,
|
|
202
|
+
output_format='summary'
|
|
203
|
+
)
|
|
204
|
+
print(summary)
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
**Function signature:**
|
|
208
|
+
|
|
209
|
+
```python
|
|
210
|
+
summarize_json_structure(
|
|
211
|
+
source: str,
|
|
212
|
+
from_file: bool = True,
|
|
213
|
+
output_format: Literal['schema', 'summary'] = 'schema',
|
|
214
|
+
pretty: bool = False,
|
|
215
|
+
max_samples: Optional[int] = None,
|
|
216
|
+
return_type: Literal['str', 'dict'] = 'str'
|
|
217
|
+
) -> Union[str, Dict]
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
---
|
|
221
|
+
|
|
222
|
+
## License
|
|
223
|
+
|
|
224
|
+
MIT License – see [LICENSE](LICENSE) for details.
|
|
225
|
+
|
|
226
|
+
---
|
|
227
|
+
|
|
228
|
+
## Contributing
|
|
229
|
+
|
|
230
|
+
Bug reports, feature requests, and pull requests are welcome on [GitHub](https://github.com/akingdom/json-structure-summary).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
json_structure_summary/__init__.py,sha256=92FfbzuqLQ129gBo0kUzYxwNEhbEqUYEk8GLfxBRxs0,253
|
|
2
|
+
json_structure_summary/core.py,sha256=slsA1BU9PqJw2pl1jpuMNw9mPnLEZUOgAGbC4tb-id4,14537
|
|
3
|
+
json_structure_summary-0.1.0.dist-info/licenses/LICENSE.md,sha256=3PS64E9B4QMAlNM47CgxOtGQm3mEfvDIOmSde6rJObU,1071
|
|
4
|
+
json_structure_summary-0.1.0.dist-info/METADATA,sha256=Yq9pyrKYq3KzFQMQSDpTm6eVcw8lqBiVu6zAb0X39TU,6813
|
|
5
|
+
json_structure_summary-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
6
|
+
json_structure_summary-0.1.0.dist-info/entry_points.txt,sha256=v9G9zoeC2sRzTByjOyWTgybmWE4Op-GG_HtPhCehm_c,71
|
|
7
|
+
json_structure_summary-0.1.0.dist-info/top_level.txt,sha256=fZyCh0_r-OKzRvuih2W6lJ8Q-DdtgKFl9OZ7MVSHiO8,23
|
|
8
|
+
json_structure_summary-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Andrew Kingdom
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
json_structure_summary
|