Validate JSON Input for a Tiny AI Dataset
Validate a labelled text dataset before training by rejecting malformed JSON, duplicated keys and rows with unexpected types or labels.
Difficulty Beginner
Prepare a small dataset
Use Python 3 and a text editor. No GPU or third-party package is required. Make a sample.json file with two fictional messages, each labelled by hand.
[
{"text": "When does the lab open?", "label": "question"},
{"text": "The lab is open today.", "label": "statement"}
]
Validate the structure
Save this as validate.py and run python3 validate.py from the same directory.
import json
from pathlib import Path
def reject_duplicate_keys(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError(f"duplicate key: {key}")
result[key] = value
return result
try:
rows = json.loads(
Path("sample.json").read_text(encoding="utf-8"),
object_pairs_hook=reject_duplicate_keys,
)
if not isinstance(rows, list) or not rows:
raise ValueError("expected a non-empty array")
for number, row in enumerate(rows, 1):
if not isinstance(row, dict) or row.keys() != {"text", "label"}:
raise ValueError(f"row {number}: expected text and label")
if not isinstance(row["text"], str) or not row["text"].strip():
raise ValueError(f"row {number}: expected non-empty text")
label = row["label"]
if not isinstance(label, str) or label not in ("question", "statement"):
raise ValueError(f"row {number}: unknown label")
except (OSError, ValueError) as error:
raise SystemExit(f"Validation failed: {error}")
print(f"Accepted {len(rows)} rows.")
Syntax parsing comes first. The object hook prevents later keys from silently overwriting earlier ones. The row checks enforce fields and types. A valid file prints Accepted 2 rows. A rejected file terminates with a nonzero exit, so a wrapper can stop before a training job begins.
Troubleshooting and practice
Try trailing commas, a duplicate label key, an array instead of a label string and a text value containing spaces only. Record the result for each separate run. If opening fails, check pwd and the exact filename before changing the script. If decoding fails, ensure the editor saves UTF-8. Use this reader for small files from known sources. Set a file-size limit before loading untrusted inputs in a real service, and keep message contents out of validation logs.