تمرين إعادة البناء
مدقق سجلات JSON
تحقق من قائمة كائنات JSON حسب مفاتيح مطلوبة وأنواع بسيطة.
python
~25 دقيقة
متوسط
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
import argparse
import json
from pathlib import Path
TYPE_MAP = {
"str": str,
"int": int,
"float": (int, float),
"bool": bool,
"list": list,
"dict": dict,
}
def parse_rule(rule: str) -> tuple[str, str]:
if ":" not in rule:
raise ValueError(f"Rule must look like key:type: {rule}")
key, type_name = rule.split(":", 1)
if type_name not in TYPE_MAP:
raise ValueError(f"Unsupported type: {type_name}")
return key, type_name
def validate_record(index: int, record: object, rules: list[tuple[str, str]]) -> list[str]:
if not isinstance(record, dict):
return [f"row {index}: not an object"]
errors = []
for key, type_name in rules:
if key not in record:
errors.append(f"row {index}: missing {key}")
elif not isinstance(record[key], TYPE_MAP[type_name]):
errors.append(f"row {index}: {key} is not {type_name}")
return errors
def main() -> None:
parser = argparse.ArgumentParser(description="Validate JSON records with simple key:type rules.")
parser.add_argument("json_file", type=Path)
parser.add_argument("rules", nargs="+")
args = parser.parse_args()
data = json.loads(args.json_file.read_text(encoding="utf-8"))
records = data if isinstance(data, list) else [data]
rules = [parse_rule(rule) for rule in args.rules]
errors = []
for index, record in enumerate(records, start=1):
errors.extend(validate_record(index, record, rules))
print("OK" if not errors else "\n".join(errors))
if __name__ == "__main__":
main()اكتب هنا