The user asked me to create a Python tool for validating and cleaning JSON data, but they provided very few details. I need to design a script or module without knowing the specific environment or interface they prefer. A solid starting point might be a command-line script that takes an input JSON file and a schema. This tool could clean data by coercing types, removing unnecessary keys, and handling nulls. I aim to keep it functional yet concise, offering a one-file script with appropriate code and explanations. I wonder if I should ask clarifying questions, but I think it’s okay to propose a general tool.Outlining validation and cleaning
I need to clarify what "validate and clean" means for the user. I'm planning to use the json and jsonschema modules. While jsonschema is external and widely used, the user might need to install it via pip, so I should mention that. It might be better to provide a tool using JSON Schema, defining per-field cleaning rules in a config. I could create a Python module, json_cleaner.py, that accepts a JSON string or Python data, validates it using jsonschema, and performs cleaning like removing extra keys, coercing types, and applying default values.Planning the clean_record function
I'm implementing a clean_record function that utilizes schema information. I want to keep the code manageable, aiming for about 150-200 lines for the library. I'd like to create both a CLI and library interface. Users could run the command like python json_cleaner.py input.json schema.json --output cleaned.json --error-log errors.jsonl.
My plan is to include a brief introduction and the following components: a shebang, necessary imports like json, argparse, pathlib, typing, and jsonschema, then define a function to load JSON data. I'll create a helper function, iter_records, to ensure we handle a list of records and another, clean_value, to recursively coerce types according to the JSON Schema specifications.Implementing the clean_value function
I'm working on the clean_value function to handle data cleaning based on the schema provided. First, I'll retrieve the type_info from the schema. If it's a list, I'll select the first type that matches.
Next, I'll handle each type specifically: for "string," I'll convert integers, floats, or booleans to strings and remove any whitespace. If it's "integer," I'll attempt to convert the value to an integer, and for "number," to a float. With "boolean," I'll map specific string values to True or False, and for "object," I'll call another function, clean_object. Lastly, for "array," I’ll ensure the value is in list format.Refining the cleaning process
I want to simplify the process for handling non-list values by wrapping them in a list if they're non-null. For null values, I'll set them to None if they're empty or already None; otherwise, I'll leave them untouched.
Next, for the clean_object function, I'll get properties from the schema and handle additionalProperties. I'll clean the object based on its properties and set up a new dictionary accordingly. This dict will contain cleaned values, checking for nulls when necessary.
I plan to use jsonschema for validation and create a command-line interface to handle input, schema, and error logging, allowing users to specify flags for dropping or keeping invalid records easily. I'll ensure the script runs smoothly even without jsonschema, with a helpful installation prompt if needed. I’m excited to draft the code now!Creating the JSON validation and cleaning script
To create a Python tool for validating and cleaning JSON data, I'll begin by loading the schema file and the input data. If the data is a list, I’ll process it accordingly, using the clean_value function to ensure each record conforms to the schema.
For validation, I'll use the Draft7Validator, collecting any errors encountered during this process. If specified, I'll write the valid records to an output file and log errors as JSON lines.
You can install the necessary jsonschema library with pip install jsonschema. Here’s an example schema you might use:
And here's how the script structure looks with essential functions for loading JSON, cleaning data, applying defaults, and validating records. Below is a self‑contained Python script that:
Loads JSON data and a JSON Schema
Cleans/coerces values based on the schema
Applies defaults from the schema
Validates with jsonschema
Writes out a cleaned JSON file and an optional error log
You can use it both as a CLI tool and as an importable module.
cleaned.json will contain cleaned, schema-valid records. errors.jsonl (if any) will list invalid records with human-readable validation errors.
You can also import and use the functions programmatically:
python
from json_cleaner import clean_value, validate_records
schema = ...
data = ...
cleaned = [clean_value(rec, schema) for rec in data]
valid, errors = validate_records(cleaned, schema)
If you want more specific cleaning rules (e.g., date parsing, custom normalizations), those can be added into clean_value based on schema keywords (like "format": "date-time") or custom extension fields.
#!/usr/bin/env python3
"""
json_cleaner.py
Validate and clean JSON data using a JSON Schema.
Features:
- Type coercion (e.g., "123" -> 123 for integer fields, "true" -> True)
- Trimming strings
- Filling in default values from the schema
- Dropping unknown properties if schema has "additionalProperties": false
- Validation with jsonschema (Draft 7)
Usage:
python json_cleaner.py input.json schema.json -o cleaned.json -e errors.jsonl
Requires:
pip install jsonschema
"""
import argparse
import json
import sys
from pathlib import Path
from typing import Any, Dict, Iterable, List, Tuple
try:
from jsonschema import Draft7Validator
except ImportError:
sys.exit(
"This tool requires the 'jsonschema' package.\n"
"Install it with:\n pip install jsonschema"
)
Json = Any
# ----------------------------------------------------------------------
# Core cleaning logic
# ----------------------------------------------------------------------
def apply_defaults(target: Dict[str, Any], schema: Dict[str, Any]) -> None:
"""Apply default values from schema to missing properties in target."""
for prop, prop_schema in schema.get("properties", {}).items():
if "default" in prop_schema and prop not in target:
target[prop] = prop_schema["default"]
def clean_object(obj: Dict[str, Any], schema: Dict[str, Any]) -> Dict[str, Any]:
"""Clean a JSON object according to an object schema."""
props = schema.get("properties", {})
additional = schema.get("additionalProperties", True)
result: Dict[str, Any] = {}
# First, populate defaults
apply_defaults(result, schema)
# Now, process existing keys
for key, val in obj.items():
if key in props:
result[key] = clean_value(val, props[key])
else:
# Handle additional properties
if additional is False:
# Drop unknown properties
continue
if isinstance(additional, dict):
# Clean according to additionalProperties subschema
result[key] = clean_value(val, additional)
else:
# Keep as-is
result[key] = val
return result
def _pick_type(type_decl: Any) -> Any:
"""Pick a preferred type from a JSON Schema 'type' declaration."""
if isinstance(type_decl, list) and type_decl:
# Prefer non-null type if present
non_null = [t for t in type_decl if t != "null"]
return non_null[0] if non_null else type_decl[0]
return type_decl
def clean_value(value: Any, schema: Dict[str, Any]) -> Any:
"""Recursively clean a value according to its schema."""
t = _pick_type(schema.get("type"))
# Handle object / array first if explicitly declared
if t == "object":
if isinstance(value, dict):
return clean_object(value, schema)
return value
if t == "array":
if value is None:
return None
if not isinstance(value, list):
# Wrap single value into a list
value = [value]
item_schema = schema.get("items", {})
return [clean_value(v, item_schema) for v in value]
# Scalars
if t == "string":
if value is None:
return None
if isinstance(value, (int, float, bool)):
return str(value)
if isinstance(value, str):
v = value.strip()
return v
return value
if t == "integer":
if value in ("", None):
return None
try:
return int(value)
except (ValueError, TypeError):
return value
if t == "number":
if value in ("", None):
return None
try:
return float(value)
except (ValueError, TypeError):
return value
if t == "boolean":
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return bool(value)
if isinstance(value, str):
v = value.strip().lower()
if v in {"true", "1", "yes", "y", "t"}:
return True
if v in {"false", "0", "no", "n", "f"}:
return False
return value
if t == "null":
# Convert empty string to None
if value == "" or value is None:
return None
return value
# If type is not declared, try nested schemas
if isinstance(value, dict) and "properties" in schema:
return clean_object(value, schema)
if isinstance(value, list) and "items" in schema:
item_schema = schema.get("items", {})
return [clean_value(v, item_schema) for v in value]
return value
# ----------------------------------------------------------------------
# Validation
# ----------------------------------------------------------------------
def validate_records(
records: Iterable[Json],
schema: Dict[str, Any]
) -> Tuple[List[Json], List[Dict[str, Any]]]:
"""
Validate records against a schema.
Returns:
valid_records, error_details
"""
validator = Draft7Validator(schema)
valid: List[Json] = []
errors: List[Dict[str, Any]] = []
for idx, rec in enumerate(records):
rec_errors = sorted(validator.iter_errors(rec), key=lambda e: e.path)
if rec_errors:
errors.append({
"index": idx,
"record": rec,
"errors": [
{
"path": "/".join(str(p) for p in e.path) or "<root>",
"message": e.message,
}
for e in rec_errors
],
})
else:
valid.append(rec)
return valid, errors
# ----------------------------------------------------------------------
# I/O helpers
# ----------------------------------------------------------------------
def load_json_file(path: Path) -> Json:
try:
return json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as e:
sys.exit(f"Failed to parse JSON from {path}:\n{e}")
def write_json_file(path: Path, data: Json) -> None:
path.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
def write_jsonl_file(path: Path, records: Iterable[Json]) -> None:
with path.open("w", encoding="utf-8") as f:
for rec in records:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
def ensure_records(data: Json) -> List[Json]:
"""Ensure the root is a list of records."""
if isinstance(data, list):
return data
return [data]
# ----------------------------------------------------------------------
# CLI
# ----------------------------------------------------------------------
def parse_args(argv: List[str]) -> argparse.Namespace:
p = argparse.ArgumentParser(
description="Validate and clean JSON data using a JSON Schema."
)
p.add_argument("input", type=Path, help="Input JSON file (object or array of objects)")
p.add_argument("schema", type=Path, help="JSON Schema file")
p.add_argument(
"-o", "--output", type=Path, default=Path("cleaned.json"),
help="Output file for cleaned, valid data (default: cleaned.json)",
)
p.add_argument(
"-e", "--errors", type=Path, default=None,
help="Optional JSON Lines file to write validation errors",
)
return p.parse_args(argv)
def main(argv: List[str]) -> None:
args = parse_args(argv)
schema = load_json_file(args.schema)
raw_data = load_json_file(args.input)
records = ensure_records(raw_data)
# Clean according to schema
cleaned_records = [clean_value(rec, schema) for rec in records]
# Validate
valid_records, error_details = validate_records(cleaned_records, schema)
# Write cleaned valid records
if len(valid_records) == 1:
write_json_file(args.output, valid_records[0])
else:
write_json_file(args.output, valid_records)
# Write errors if requested
if args.errors:
write_jsonl_file(args.errors, error_details)
# Basic summary to stderr
print(
f"Input records: {len(records)} | "
f"Valid: {len(valid_records)} | "
f"Invalid: {len(error_details)}",
file=sys.stderr,
)
if args.errors and error_details:
print(f"Validation errors written to: {args.errors}", file=sys.stderr)
print(f"Cleaned data written to: {args.output}", file=sys.stderr)
if __name__ == "__main__":
main(sys.argv[1:])