The user wants a Python tool to validate and clean JSON data.
I need to decide on the scope and functionality of this tool.
"Validate" usually means checking if the string is valid JSON and if it adheres to a schema (optional but good).
"Clean" usually means:
Removing keys with null values.
Stripping whitespace from strings.
Converting data types (e.g., string numbers to integers).
Removing duplicate keys (though valid JSON shouldn't have them, parsing them often keeps the last one).
Normalizing structure (sorting keys).
I will create a Python script that offers a class or set of functions to perform these operations.
Plan:
Core Functionality:
Load JSON from string or file.
Validation: Check for json.JSONDecodeError. Check against a JSON Schema (optional, maybe add as an advanced feature).
I'll create a class JSONCleaner for state management (loading data).
I'll include a command-line interface (CLI) using argparse so it can be used as a standalone tool.
Refining the Cleaning Logic:
Recursive approach: Since JSON is nested, I need a recursive function to traverse lists and dictionaries.
Configurability: Allow the user to toggle specific cleaning rules (e.g., "don't remove nulls", "don't convert types").
Drafting the Code (Mental or scratchpad):
Input:dirty_json_str or dirty_dict.
Recursive cleaner function:
python
def clean(value, config):
if isinstance(value, dict):
# iterate, clean children, check drop conditions
new_dict = {}
for k, v in value.items():
cleaned_v = clean(v, config)
if should_drop(cleaned_v, config): continue
new_dict[k] = cleaned_v
return new_dict
elif isinstance(value, list):
# iterate, clean children, check drop conditions
new_list = []
for item in value:
cleaned_item = clean(item, config)
if should_drop(cleaned_item, config): continue
new_list.append(cleaned_item)
return new_list
elif isinstance(value, str):
# strip
# try convert to number/bool
else:
return value
Adding Validation:
Standard library json module handles syntax validation.
I should mention jsonschema for structural validation, but maybe keep the core dependency-free for simplicity, or offer jsonschema as an optional import. Decision: I will stick to the standard library for the core logic to make it portable, but I will add a method that accepts a schema if the user has that library installed.
It's often risky to automatically convert types (e.g., ID "001" should stay string). I will make type conversion an opt-in feature or very explicit.
Removing empty lists/dicts is a common request.
Final Code Structure:
A reusable class.
A helper script usage example.
Comments explaining how to use it.
Let's write the actual code.
Self-Correction during drafting: A simple function approach is good, but a class allows chaining (.load().clean().save()). I'll provide a comprehensive script that does both: exposes a class for library use and a main() for CLI use.
Cleaning Logic Detail:
strip_strings: " foo " -> "foo"
remove_nulls: {"a": null} -> {}
remove_empty: {"a": [], "b": {}} -> {} (nested)
convert_types: "123" -> 123.
Let's assemble the solution.
Feature List for the Tool:
Validation: Parses JSON to ensure syntax correctness.
Trimming: Strips leading/trailing whitespace from string values.
Type Casting (Optional): Attempts to convert string numbers to integers/floats.
Schema Validation (Optional): Uses jsonschema if available.
I will focus on a robust, dependency-free (standard lib) implementation first, with schema validation as a bonus check.
Drafting the recursive function:
python
def _clean_data(self, data):
if isinstance(data, dict):
return {k: self._clean_data(v) for k, v in data.items() if not self._is_empty(v)}
# ... and so on
Need to be careful: if we remove empty items, we might break data structures that expect empty arrays. I will make this configurable via flags.
Let's finalize the output format. A single Python file is best.
Here is a comprehensive, dependency-free Python tool to validate and clean JSON data. It includes a reusable class for integration into other scripts and a command-line interface (CLI) for direct file manipulation.
The Python Tool (json_cleaner.py)
You can save the following code as a file (e.g., json_cleaner.py) or incorporate the JSONCleaner class into your existing project.
python
How to use this tool
There are two ways to use this: as a Command Line Tool or as a Python Library in your code.
1. Command Line Usage
Save the code above as json_cleaner.py. You can then run it from your terminal.
Basic Validation & Formatting:
Reads a file, checks if it is valid JSON, and prints it nicely formatted.
You can import the JSONCleaner class into your own Python projects to handle API responses or configuration files.
python
from json_cleaner import JSONCleaner
# 1. Define some messy JSON data
messy_json = """
{
"id": " 123 ",
"name": "Alice",
"email": null,
"active": "true",
"orders": [],
"score": "98.5"
}
"""
# 2. Initialize the cleaner with options
cleaner = JSONCleaner(
remove_nulls=True, # Removes email: null
remove_empty=True, # Removes orders: []
trim_strings=True, # Cleans " 123 " -> "123"
auto_convert_types=True # "true" -> true, "98.5" -> 98.5
)
try:
# 3. Process
clean_data = cleaner.process(messy_json)
# 4. Result
print(cleaner.to_json_string(clean_data))
except ValueError as e:
print(f"The data was invalid: {e}")
Key Features Explained
Validation: It uses Python's built-in json library to ensure the structure is valid. If invalid, it raises a clear error message indicating the line and column of the failure.
Cleaning Logic:
Recursive: It handles deeply nested lists and dictionaries.
Safe Type Conversion: It uses Regex to identify numbers and booleans safely without breaking version numbers like "v1.00".
Memory Efficient: For the command line tool, it reads files line-by-line where possible, though full JSON parsing requires loading the structure into memory.
import json
import argparse
import sys
import re
from datetime import datetime
class JSONCleaner:
"""
A class to validate and clean JSON data.
"""
def __init__(self, remove_nulls=False, remove_empty=False, trim_strings=True, auto_convert_types=False):
"""
Initialize cleaning preferences.
:param remove_nulls: Remove keys with None/null values.
:param remove_empty: Remove keys with empty strings, lists, or dicts.
:param trim_strings: Strip leading/trailing whitespace from strings.
:param auto_convert_types: Attempt to convert string numbers/booleans to native types.
"""
self.remove_nulls = remove_nulls
self.remove_empty = remove_empty
self.trim_strings = trim_strings
self.auto_convert_types = auto_convert_types
def validate(self, json_data):
"""
Validates if the input is valid JSON.
:param json_data: String or file-like object containing JSON.
:return: Tuple (is_valid, parsed_data_or_error_message)
"""
try:
if isinstance(json_data, str):
data = json.loads(json_data)
else:
# Assume file-like object
data = json.load(json_data)
return True, data
except json.JSONDecodeError as e:
return False, f"Validation Error: {e.msg} at line {e.lineno} column {e.colno}"
except Exception as e:
return False, f"General Error: {str(e)}"
def _convert_value(self, value):
"""Helper to attempt type conversion."""
if not isinstance(value, str):
return value
v = value.lower()
# Handle Booleans
if v == 'true':
return True
if v == 'false':
return False
# Handle Nulls (strings like "null" becoming None)
if v == 'null':
return None
# Handle Numbers (Integers and Floats)
# Regex checks for valid number format (including negatives and scientific notation)
if re.match(r'^-?\d+(\.\d+)?([eE][+-]?\d+)?$', value):
try:
if '.' in value or 'e' in value.lower():
return float(value)
return int(value)
except ValueError:
return value
return value
def _should_remove(self, value):
"""Determine if a value should be removed based on config."""
if self.remove_nulls and value is None:
return True
if self.remove_empty:
if value == "": return True
if isinstance(value, (list, dict)) and len(value) == 0: return True
return False
def _clean_recursive(self, data):
"""
Recursively clean data structure.
"""
if isinstance(data, dict):
cleaned_dict = {}
for key, value in data.items():
# Clean key if string
if self.trim_strings and isinstance(key, str):
key = key.strip()
# Recurse value
value = self._clean_recursive(value)
# Type conversion
if self.auto_convert_types and isinstance(value, str):
value = self._convert_value(value)
# Removal logic
if self._should_remove(value):
continue
cleaned_dict[key] = value
return cleaned_dict
elif isinstance(data, list):
cleaned_list = []
for item in data:
item = self._clean_recursive(item)
# Note: We usually don't remove items from lists based on value
# to preserve indices, unless specific logic is requested.
# Here we just clean the contents.
if self._should_remove(item):
# Optional: uncomment below to remove 'empty' items from lists too
# continue
pass
cleaned_list.append(item)
return cleaned_list
elif isinstance(data, str):
if self.trim_strings:
data = data.strip()
if self.auto_convert_types:
data = self._convert_value(data)
return data
else:
return data
def process(self, input_data):
"""
Validates and Cleans the input data.
:param input_data: JSON string or Python dict/list.
:return: Cleaned Python object or raises ValueError.
"""
# 1. Validate
is_valid, result = self.validate(input_data)
if not is_valid:
raise ValueError(result)
# 2. Clean
cleaned_data = self._clean_recursive(result)
return cleaned_data
def to_json_string(self, data, indent=2):
"""Helper to dump result back to string."""
return json.dumps(data, indent=indent, ensure_ascii=False)
def main():
parser = argparse.ArgumentParser(description="JSON Validator & Cleaner Tool")
parser.add_argument('input_file', type=str, nargs='?', help="Path to input JSON file. Defaults to stdin.")
parser.add_argument('-o', '--output', type=str, help="Path to output file. Defaults to stdout.")
# Cleaning Flags
parser.add_argument('--remove-nulls', action='store_true', help="Remove keys with null values.")
parser.add_argument('--remove-empty', action='store_true', help="Remove keys with empty strings, lists, or dicts.")
parser.add_argument('--trim', action='store_true', default=True, help="Trim whitespace from strings (Default: True).")
parser.add_argument('--auto-convert', action='store_true', help="Convert stringified numbers/booleans to native types.")
args = parser.parse_args()
cleaner = JSONCleaner(
remove_nulls=args.remove_nulls,
remove_empty=args.remove_empty,
trim_strings=args.trim,
auto_convert_types=args.auto_convert
)
input_content = ""
# Read Input
try:
if args.input_file:
with open(args.input_file, 'r', encoding='utf-8') as f:
input_content = f.read()
else:
# Read from pipe/stdin
if not sys.stdin.isatty():
input_content = sys.stdin.read()
else:
parser.print_help()
sys.exit(1)
except FileNotFoundError:
print(f"Error: File '{args.input_file}' not found.", file=sys.stderr)
sys.exit(1)
# Process
try:
cleaned_data = cleaner.process(input_content)
output_str = cleaner.to_json_string(cleaned_data)
# Write Output
if args.output:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(output_str)
print(f"Success: Cleaned JSON saved to {args.output}")
else:
print(output_str)
except ValueError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()