JSON Mini Project: Product Catalog Cleanup
In this project you'll combine everything from the course. A supplier has sent a product catalog as JSON — but it was exported by an old system, and the data is messy. Your job is to build a small pipeline that:
- Parses the raw export safely.
- Validates every product against a set of rules.
- Transforms valid products into a clean, consistent format.
- Reports problems and outputs clean JSON plus a summary.
Each step is a runnable playground. Later steps repeat the earlier code so that every playground works on its own.
Step 0: Look at the raw data
Run the export through the validator first. It's syntactically valid JSON — the problems are in the content:
{
"exportedAt": "2025-04-30T23:59:00Z",
"currency": "USD",
"items": [
{"SKU": "tea-001", "Name": " Green Tea ", "Price": "4.50", "Stock": 120, "Tags": "drinks,organic"},
{"SKU": "lamp-07", "Name": "Desk Lamp", "Price": 18, "Stock": "8", "Tags": "home"},
{"SKU": "", "Name": "Mystery Box", "Price": 9.99, "Stock": 3, "Tags": ""},
{"SKU": "mug-002", "Name": "Coffee Mug", "Price": -6, "Stock": 40, "Tags": "kitchen"},
{"SKU": "pen-010", "Name": "Gel Pen", "Price": "1.2", "Stock": null, "Tags": "office, writing"},
{"SKU": "tea-001", "Name": "Green Tea (dup)", "Price": 4.5, "Stock": 1, "Tags": "drinks"}
]
}Valid JSON: object with 3 keys
{
"exportedAt": "2025-04-30T23:59:00Z",
"currency": "USD",
"items": [
{
"SKU": "tea-001",
"Name": " Green Tea ",
"Price": "4.50",
"Stock": 120,
"Tags": "drinks,organic"
},
{
"SKU": "lamp-07",
"Name": "Desk Lamp",
"Price": 18,
"Stock": "8",
"Tags": "home"
},
{
"SKU": "",
"Name": "Mystery Box",
"Price": 9.99,
"Stock": 3,
"Tags": ""
},
{
"SKU": "mug-002",
"Name": "Coffee Mug",
"Price": -6,
"Stock": 40,
"Tags": "kitchen"
},
{
"SKU": "pen-010",
"Name": "Gel Pen",
"Price": "1.2",
"Stock": null,
"Tags": "office, writing"
},
{
"SKU": "tea-001",
"Name": "Green Tea (dup)",
"Price": 4.5,
"Stock": 1,
"Tags": "drinks"
}
]
}
Problems you can spot: keys in PascalCase, prices as strings, stock as a string or null, comma-separated tags, extra spaces, an empty SKU, a negative price and a duplicate SKU.
Step 1: Define the target format
Every clean product should look like this — a mini JSON Schema in words:
| Key | Type | Rule |
|---|---|---|
sku |
string | non-empty, uppercase, unique |
name |
string | trimmed, non-empty |
price |
number | > 0, rounded to 2 decimals |
stock |
integer | ≥ 0 (missing stock counts as 0) |
tags |
array of strings | lowercase, trimmed, no empty entries |
inStock |
boolean | stock > 0 |
Step 2: Normalise one product
Write a function that converts a raw item into the target shape, without rejecting anything yet:
function normalise(raw) {
const stock = raw.Stock === null || raw.Stock === undefined ? 0 : Number(raw.Stock);
return {
sku: String(raw.SKU ?? "").trim().toUpperCase(),
name: String(raw.Name ?? "").trim(),
price: Math.round(Number(raw.Price) * 100) / 100,
stock,
tags: String(raw.Tags ?? "")
.split(",")
.map((t) => t.trim().toLowerCase())
.filter(Boolean),
inStock: stock > 0,
};
}
console.log(normalise({ SKU: "tea-001", Name: " Green Tea ", Price: "4.50", Stock: 120, Tags: "drinks,organic" }));
console.log(normalise({ SKU: "pen-010", Name: "Gel Pen", Price: "1.2", Stock: null, Tags: "office, writing" }));{
sku: 'TEA-001',
name: 'Green Tea',
price: 4.5,
stock: 120,
tags: [ 'drinks', 'organic' ],
inStock: true
}
{
sku: 'PEN-010',
name: 'Gel Pen',
price: 1.2,
stock: 0,
tags: [ 'office', 'writing' ],
inStock: false
}
Step 3: Validate
The validator returns a list of error messages for one normalised product. Uniqueness needs to know which SKUs were already seen, so we pass in a Set:
function validateProduct(p, seenSkus) {
const errors = [];
if (!p.sku) errors.push("missing sku");
else if (seenSkus.has(p.sku)) errors.push(`duplicate sku ${p.sku}`);
if (!p.name) errors.push("missing name");
if (!Number.isFinite(p.price) || p.price <= 0) errors.push(`invalid price ${p.price}`);
if (!Number.isInteger(p.stock) || p.stock < 0) errors.push(`invalid stock ${p.stock}`);
return errors;
}
const seen = new Set(["TEA-001"]);
console.log(validateProduct({ sku: "", name: "Box", price: 9.99, stock: 3 }, seen));
console.log(validateProduct({ sku: "MUG-002", name: "Mug", price: -6, stock: 40 }, seen));
console.log(validateProduct({ sku: "TEA-001", name: "Tea", price: 4.5, stock: 1 }, seen));
console.log(validateProduct({ sku: "LAMP-07", name: "Lamp", price: 18, stock: 8 }, seen));[ 'missing sku' ]
[ 'invalid price -6' ]
[ 'duplicate sku TEA-001' ]
[]
Step 4: The full pipeline
Now put it together: parse → normalise → validate → split into accepted and rejected → summarise → stringify.
const rawText = `{
"exportedAt": "2025-04-30T23:59:00Z",
"currency": "USD",
"items": [
{"SKU": "tea-001", "Name": " Green Tea ", "Price": "4.50", "Stock": 120, "Tags": "drinks,organic"},
{"SKU": "lamp-07", "Name": "Desk Lamp", "Price": 18, "Stock": "8", "Tags": "home"},
{"SKU": "", "Name": "Mystery Box", "Price": 9.99, "Stock": 3, "Tags": ""},
{"SKU": "mug-002", "Name": "Coffee Mug", "Price": -6, "Stock": 40, "Tags": "kitchen"},
{"SKU": "pen-010", "Name": "Gel Pen", "Price": "1.2", "Stock": null, "Tags": "office, writing"},
{"SKU": "tea-001", "Name": "Green Tea (dup)", "Price": 4.5, "Stock": 1, "Tags": "drinks"}
]
}`;
function normalise(raw) {
const stock = raw.Stock === null || raw.Stock === undefined ? 0 : Number(raw.Stock);
return {
sku: String(raw.SKU ?? "").trim().toUpperCase(),
name: String(raw.Name ?? "").trim(),
price: Math.round(Number(raw.Price) * 100) / 100,
stock,
tags: String(raw.Tags ?? "").split(",").map((t) => t.trim().toLowerCase()).filter(Boolean),
inStock: stock > 0,
};
}
function validateProduct(p, seenSkus) {
const errors = [];
if (!p.sku) errors.push("missing sku");
else if (seenSkus.has(p.sku)) errors.push(`duplicate sku ${p.sku}`);
if (!p.name) errors.push("missing name");
if (!Number.isFinite(p.price) || p.price <= 0) errors.push(`invalid price ${p.price}`);
if (!Number.isInteger(p.stock) || p.stock < 0) errors.push(`invalid stock ${p.stock}`);
return errors;
}
let source;
try {
source = JSON.parse(rawText);
} catch (err) {
console.log("Cannot read export:", err.message);
throw err;
}
const accepted = [];
const rejected = [];
const seen = new Set();
source.items.forEach((raw, index) => {
const product = normalise(raw);
const errors = validateProduct(product, seen);
if (errors.length) {
rejected.push({ index, sku: product.sku || null, errors });
} else {
seen.add(product.sku);
accepted.push(product);
}
});
const catalog = {
currency: source.currency,
generatedFrom: source.exportedAt,
count: accepted.length,
totalStockValue: Math.round(accepted.reduce((sum, p) => sum + p.price * p.stock, 0) * 100) / 100,
products: accepted.sort((a, b) => a.sku.localeCompare(b.sku)),
};
console.log("Rejected:");
for (const r of rejected) console.log(` #${r.index} ${r.sku ?? "(no sku)"}: ${r.errors.join("; ")}`);
console.log();
console.log(JSON.stringify(catalog, null, 2));Rejected:
#2 (no sku): missing sku
#3 MUG-002: invalid price -6
#5 TEA-001: duplicate sku TEA-001
{
"currency": "USD",
"generatedFrom": "2025-04-30T23:59:00Z",
"count": 3,
"totalStockValue": 684,
"products": [
{
"sku": "LAMP-07",
"name": "Desk Lamp",
"price": 18,
"stock": 8,
"tags": [
"home"
],
"inStock": true
},
{
"sku": "PEN-010",
"name": "Gel Pen",
"price": 1.2,
"stock": 0,
"tags": [
"office",
"writing"
],
"inStock": false
},
{
"sku": "TEA-001",
"name": "Green Tea",
"price": 4.5,
"stock": 120,
"tags": [
"drinks",
"organic"
],
"inStock": true
}
]
}
Three products survived, three were rejected with clear reasons, and the output is clean JSON that any other program can trust.
Step 5: Double-check with Python
A good habit is to verify the output with a different tool. This Python script reads the clean catalog and re-checks the rules independently:
import json
catalog_text = '''
{"currency": "USD", "count": 3, "products": [
{"sku": "LAMP-07", "name": "Desk Lamp", "price": 18, "stock": 8, "tags": ["home"], "inStock": true},
{"sku": "PEN-010", "name": "Gel Pen", "price": 1.2, "stock": 0, "tags": ["office", "writing"], "inStock": false},
{"sku": "TEA-001", "name": "Green Tea", "price": 4.5, "stock": 120, "tags": ["drinks", "organic"], "inStock": true}
]}
'''
catalog = json.loads(catalog_text)
problems = []
skus = [p["sku"] for p in catalog["products"]]
if len(skus) != len(set(skus)):
problems.append("duplicate SKUs")
if catalog["count"] != len(catalog["products"]):
problems.append("count mismatch")
for p in catalog["products"]:
if p["price"] <= 0:
problems.append(f"{p['sku']}: bad price")
if p["inStock"] != (p["stock"] > 0):
problems.append(f"{p['sku']}: inStock flag wrong")
if any(t != t.strip().lower() for t in p["tags"]):
problems.append(f"{p['sku']}: tags not normalised")
print("OK" if not problems else problems)
print("Out of stock:", [p["sku"] for p in catalog["products"] if not p["inStock"]])
print("Value:", round(sum(p["price"] * p["stock"] for p in catalog["products"]), 2))OK
Out of stock: ['PEN-010']
Value: 684.0
Both tools agree on the stock value, so the pipeline is consistent.
Ideas to extend the project
- Export the rejected items as JSON Lines so a colleague can fix them one by one.
- Describe the target format as a real JSON Schema and validate with your mini validator from the JSON Schema lesson.
- Add a
slugfield generated from the name ("Green Tea"→"green-tea"). - Write the
jqcommand that lists all SKUs withinStock == false. - Render the clean catalog as an HTML table (see JSON to HTML) using
textContent.
Test yourself
Why does the pipeline normalise products before validating them?
- Validation is faster on small objects
- So rules are checked against one consistent shape and types
- JSON.parse requires it
- To sort the products
The raw item has "Price": "4.50". What type does the clean catalog use for price?
- string
- number
- integer only
- null
Why is the duplicate tea-001 rejected and not the first one?
- The second has a lower price
- SKUs are checked against the set of already accepted SKUs
- Items are processed in reverse
- Its name contains parentheses