Projects · 8 / 19 Exercise Hard

CSV to JSON validator

Objective

Create a Python program that reads CSV data, validates each row and exports the valid ones to JSON, reporting the errors.

Instructions

  • Read an integer n and then n CSV lines. The first is the header (three columns: name, age, email) and the rest are data rows. Use the csv module to read them (fields may be quoted).
  • A row is valid if it has 3 fields, the name is not empty, the age is an integer between 0 and 120 and the email matches [A-Za-z0-9_.]+@[A-Za-z0-9]+\.[a-z]{2,}.
  • Show a single line with the JSON list of valid rows (json.dumps with ensure_ascii=False), using the header names as keys and the age as a number.
  • Then, for each invalid row (numbered from 1, not counting the header) show Row K: reason, with reason wrong number of fields, empty name, invalid age or invalid email (report the first one that fails, in that order).
  • Finish with Valid: v of n.
Input
4
name,age,email
Ana,30,ana@mail.com
Luis,abc,luis@mail.com
Eva,25,eva#mail.com
Output
[{"name": "Ana", "age": 30, "email": "ana@mail.com"}]
Row 2: invalid age
Row 3: invalid email
Valid: 1 of 3

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise