Design a JSON Schema for product extraction
Design a product JSON Schema, compare contract changes against a regression corpus, and reject contradictory price fields with tested conditional rules.
By Scraipe editorial. Checked 2026-10-28.
Start with the product record your application needs
Design a product extraction schema around a specific consumer: the fields it needs, their meanings and the cases it must reject. A JSON object with plausible property names is not yet a reliable catalog record. Decide whether a price is displayed text or a normalized amount, whether a missing value may be null, and whether a field contains one value or a list.
This guide builds a small, runnable contract for product titles, displayed prices and tag lists. It validates captured data locally with a real JSON Schema validator. The fixtures are invented; they are not customer data or a live extraction result. The example requires Node 22 or later and was tested with Node 22.23.2 and Ajv 8.20.0 on 28 October 2026.
Make the field decisions explicit
| Field | Contract | Reason |
|---|---|---|
title | Required nonblank string | A catalog row without an identifiable title needs inspection. |
priceText | Required nonblank string or explicit null | Retain currency and formatting; null means the value was unavailable, not zero. |
tags | Required array of nonblank strings; empty allowed | A product may have several labels or none. One label is still an array. |
These are teaching choices, not universal product fields. If your source provides a SKU, retain and validate it under a separate field. Do not manufacture a SKU from a row index or assume titles are unique. Add availability only after deciding how to distinguish “out of stock” from “availability not captured.”
Keeping priceText as text avoids silently turning AUD 12.50 into an amount with an unknown currency. A later, separately tested transformation can produce normalized amounts; the currency-preserving price example demonstrates explicit format policies and exact decimal strings. Neither JSON Schema nor a descriptive field hint performs currency conversion.
Write a schema for the whole result array
The complete schema declares draft-07 and includes this record shape:
json
{
"type": "object",
"properties": {
"title": { "type": "string", "minLength": 1, "pattern": "\\S" },
"priceText": {
"type": ["string", "null"],
"minLength": 1,
"pattern": "\\S"
},
"tags": {
"type": "array",
"items": { "type": "string", "minLength": 1, "pattern": "\\S" }
}
},
"required": ["title", "priceText", "tags"],
"additionalProperties": false
}The downloadable file wraps that record in type: "array", with minItems: 1 and maxItems: 1000. Those are this example consumer's batch rules, not Scraipe account limits. If an empty catalog is valid for your application, deliberately change the rule and its tests after checking the collection scope.
properties specifies how a present property is validated; it does not make that property mandatory. required checks presence. priceText: null is therefore allowed, but an absent priceText key fails. For strings, minLength: 1 rejects empty text while pattern: "\\S" requires a non-whitespace character. The string constraints do not reject the explicitly permitted null.
additionalProperties: false rejects unexpected fields so a changed payload is reviewed instead of silently discarded. It is a policy choice: when you intentionally extend the contract, version the schema and update downstream storage. The description annotations in the full file explain field meaning; they do not prove that the extracted value matches that meaning.
Run the validator and failure cases
Download these six files into one fresh directory:
- package.json
- package-lock.json
- products.schema.json
- products.fixture.json
- validate-products.mjs
- validate-products.test.mjs
Then run:
bash
npm ci --ignore-scripts --no-fund --no-audit
npm test
node validate-products.mjs products.fixture.jsonThe install downloads the pinned validator dependencies; the tests and validator make no network requests and spend no Scraipe credits. The expected test result is ten passes. The fixture command prints:
json
{ "valid": true, "rows": 2, "issueCount": 0, "issues": [] }One fixture product has priceText: "AUD 12.50" and two tags. The other has an explicit null price and no tags. Change a price to numeric 0: the report becomes invalid rather than converting it into text. Delete priceText instead of setting it to null, replace the tags array with a string, or add an unexpected property to exercise other failures.
The CLI exits 0 for valid data, 1 for a validation report containing issues and 2 for an unreadable, oversized or syntactically invalid capture. It expects the product array itself, not the API response envelope. Reports include a row count, total issue count and at most twenty path/keyword diagnostics. The full schema is applied to every record, including records after the fifth; errors are not evidence that partial import is safe.
The Ajv configuration disables coercion, default insertion and additional-property removal. Input data remains unchanged. A default annotation is not a source value, and validator-specific mutation options should not quietly fill a missing price. See the missing-field guide for the difference between absence, null, blank text and a legitimate zero.
Compare a proposed schema against a regression corpus
A schema change can reject old captures or admit new shapes even when a few example products still pass. The version-1 regression pack adds twelve named cases and a baseline-versus-candidate runner to the validator above. It is a separate tool for reviewing a proposed contract; it does not replace products.schema.json or change the Scraipe API.
The proposed candidate makes two deliberate changes: it permits an optional, nonblank sku, and it requires tag values to be unique with uniqueItems: true. The second change rejects a previously accepted duplicate-tag record. That may be useful for one consumer, but it requires an explicit data/migration decision. The pack does not approve it for you or silently deduplicate source data.
Keep the original six files, then download these additional files into the same directory:
The checksum list covers the ten files used by this regression pack plus the four cross-field files introduced below, not itself. Download all fourteen files before running the checksum command. On macOS, verify the downloaded bytes with shasum -a 256 -c SHA256SUMS.txt; on systems with GNU coreutils use sha256sum -c SHA256SUMS.txt. A matching checksum detects a file mismatch against the supplied list. It is not an independent signature or proof that a compromised source is trustworthy.
From a fresh directory containing only those downloads, run:
bash
npm ci --ignore-scripts --no-fund --no-audit
npm test
node --test schema-corpus.test.mjs
node run-schema-corpus.mjs products.schema.json candidate.schema.json schema-corpus.jsonThe original ten validator tests and eight new runner tests should pass. The corpus command emits twelve individual decisions with this summary:
json
{
"corpusVersion": 1,
"caseCount": 12,
"mismatches": 0,
"acceptanceChanges": 2
}Zero mismatches means the measured decisions match the explicit expectations saved with the cases. It does not mean the schemas are interchangeable: two known acceptance changes are present. Review the per-case outcomes, not only the process exit code.
| Case | Baseline | Candidate | What it demonstrates |
|---|---|---|---|
| Ordinary product or explicit null price | Accept | Accept | Existing permitted shapes remain covered |
Product with nonblank sku | Reject | Accept | An explicit extension admits a new property |
| Duplicate tag strings | Accept | Reject | A constraint tightens the consumer contract |
| Missing price, numeric price or blank title | Reject | Reject | Required/type/content rules remain enforced |
| Bad title in the sixth record | Reject | Reject | The full array is checked, not a five-row sample |
| Empty batch | Reject | Reject | The example's minimum batch size still applies |
The corpus also tests scalar tags, an unknown property and a blank SKU. Each case contains invented input data plus separate Boolean expectations for the baseline and candidate. Do not rewrite expectations simply to make a failing run green. First identify whether the observed change is intentional, record the decision and add representative cases for the real consumer.
The runner compiles both schemas with separate strict Ajv instances, so even matching schema identifiers can be compared without a cache-name collision. It disables coercion, default insertion and property removal, and checks that validation left each input unchanged. A schema that fails to compile is an error, never a successful comparison. Reports contain at most five path/keyword diagnostics per schema per case; omitted diagnostics do not imply acceptance.
CLI exit 0 means all recorded expectations matched, 1 means at least one decision differed, and 2 means input or compilation failed. The eight tests exercise those paths, deliberate tightening, mutation protection, duplicate case identifiers, a sixth-row failure and identifier isolation. Tested on 19 October 2026 with Node 22.23.2 and the same pinned Ajv 8.20.0 dependencies.
Use this pack as a starting point for regression evidence. It is not a proof of backward compatibility over every possible value, a schema-diff engine, or evidence that extracted values match a website. Duplicate tags may themselves be a source-quality signal. uniqueItems checks values in that array; it does not enforce unique SKUs across products or correct parent/child relationships. Add application checks for those rules and verify important fields against the capture.
The runner accepts only 1–100 cases, and its CLI checks each input file against a 1 MiB limit after reading it into memory. Use only reviewed local schemas and fixtures: these bounds do not isolate expensive regular expressions or hostile schemas, and the runner is not a streaming importer. For a real proposed change, preserve the baseline file, candidate file, corpus and checksum list with the run result so another developer can reproduce the same comparison.
Reject contradictory price fields with conditional rules
Field-level validation can accept a record whose fields disagree. Suppose a consumer adds priceState to distinguish a displayed price that was captured from a price unavailable in that capture. A string-or-null priceText plus an enum priceState still admits both "observed" with null and "unavailable" with a nonblank price. The individual types are valid; their combination violates this consumer's rule.
The new price-state example makes that relationship explicit:
| priceState | Required priceText | Meaning in this example |
|---|---|---|
observed | Nonblank string | A displayed price was captured; retain its currency and formatting. |
unavailable | Explicit null | A displayed price is unavailable in this capture. |
| Missing or another value | Reject | Inspect the capture rather than infer the state. |
These labels do not describe stock availability, free products or why extraction missed a value. An in-stock item can have no displayed price, and an out-of-stock item can still show a price. Do not infer inventory status or write zero from this field. The schema cannot establish whether the price was actually present on the source; source comparison is still necessary.
Keep the existing downloaded files and add:
Download the updated checksum list too. It now covers fourteen example files. The original product schema, validator and regression-corpus files remain unchanged. The two new schema files are teaching candidates for a different consumer contract; neither replaces the original products.schema.json automatically.
Both candidates declare priceState alongside the existing properties, require it and restrict it to observed or unavailable. The stricter candidate also adds this fragment inside its record schema:
json
{
"allOf": [
{
"if": {
"properties": { "priceState": { "const": "observed" } },
"required": ["priceState"]
},
"then": { "properties": { "priceText": { "type": "string" } } },
"else": { "properties": { "priceText": { "type": "null" } } }
}
]
}This is a fragment of the downloaded record schema, not a complete standalone schema. Its enclosing rules still require priceText, enforce nonblank strings, restrict the state enum and reject unknown properties. In particular, else is not permission for an unknown state: the enclosing enum still rejects it.
JSON Schema's draft-07 if/then/else chooses which additional constraints apply. It does not assign a value or repair data. A properties test alone accepts an absent property, so the condition includes its own required guard. The record also requires the state independently. Preserve both when adapting the fragment; otherwise an optional, absent discriminator can unexpectedly satisfy the condition.
Run the full downloaded checks in a fresh directory:
bash
npm ci --ignore-scripts --no-fund --no-audit
node --test validate-products.test.mjs schema-corpus.test.mjs price-state.test.mjs
node run-schema-corpus.mjs price-state.loose.schema.json price-state.schema.json price-state.corpus.jsonThe complete test command has 27 passes: ten original validation tests, eight original comparison tests and nine cross-field tests. The new twelve-case corpus reports mismatches: 0 and acceptanceChanges: 3. Those three changes are the two contradictory combinations and a contradiction in the sixth record. The other cases include valid observed/unavailable states, missing/unknown state, blank/numeric/missing price, an extra field and an empty batch.
As with the earlier corpus, exit 0 confirms the recorded decisions, not compatibility. This stricter candidate intentionally rejects three formerly accepted cases. The same comparison runner applies the complete array, checks for input mutation and uses strict Ajv instances with coercion/default insertion/removal disabled. All examples were rerun with Node 22.23.2 and Ajv 8.20.0 on 28 October 2026, including a fresh install from only the downloadable files.
Keep closed objects and migration decisions explicit
With draft-07 additionalProperties: false, a property introduced only in another allOf branch does not become recognized by the closed object's own properties declaration. The example declares priceState in the same record object that closes additional properties. One of the new tests demonstrates the failure if you instead attempt to extend the closed object from a separate branch. allOf combines validation requirements; it does not merge property declarations like object spread in JavaScript.
Do not overwrite the baseline schema when adopting this idea. The new contract rejects otherwise valid legacy captures because they have no priceState. Decide how the state will be collected, preserve the old capture, and validate a separately versioned candidate. Deriving observed from an existing nonnull value may describe that stored value, but cannot prove that the value matched the source or that a null represented a genuinely absent price. If that distinction matters, reinspect the source rather than filling the state automatically.
Keep failed records for review. Do not delete contradictory prices, insert default state labels or change expected corpus decisions merely to pass validation. For partial updates, the clear-intent workflow treats absence and explicit clearing separately; this example validates complete captured records and should not be applied unchanged to patches.
Use the schema with the extraction API
For a real request, the API reference accepts a schema object as an alternative to fields on POST /v1/scrape. Supply the contents of the downloaded schema, a permitted public source URL and your server-side key with the scrape scope. For example, the shape of the request is:
javascript
const requestBody = {
url: sourceUrl, // A real page you are permitted to process
schema: productSchema, // Parsed products.schema.json
maxTokens: 2000,
egress: 'direct',
};This is a request-body recipe, not a completed extraction. Keep the API origin separate from sourceUrl, keep credentials out of browser code, and begin with a small page in the playground. Compare titles, displayed prices and tag membership with the source rather than relying on a schema pass alone.
Before saving response.data to a file for this validator, inspect the envelope: success, truncation, cursor, returned/total counts and the request receipt. A response that is incomplete or failed must not be made acceptable by validating its surviving rows. The Python workflow demonstrates those envelope checks for one initial request. A continuation requires its own bounded accumulation rules.
Keep extraction checks and consumer validation separate
The current Scraipe code uses a record-level validation check during extraction. It does not enforce the entire top-level array contract there, and its runtime conformance check samples up to five records. It also permits null for optional scalar fields. A schema that its internal validator cannot compile is treated as unavailable for that check, not as proof that the data satisfies it. These implementation boundaries are why this guide validates the complete captured array independently.
The example uses draft-07, supported by Ajv's default class. Other dialects and keywords require compatible validator configuration; do not assume that declaring a 2020-12 dialect makes every extractor or validator enforce it. Keep the schema you test, the validator configuration and the deployed extraction behavior under review together.
A local source probe ran a handwritten selector specification against invented HTML and obtained a title, null missing price and two tag strings that passed the record contract. It also checked rejection of invalid required types. That proves the local selector/validator behavior for this fixture, not that the model will compile every page correctly or that the hosted service extracted a real catalog.
Inspect cost and semantic accuracy before scaling
A schema describes the data contract; it does not guarantee free compilation, successful access or complete site coverage. This recipe selects direct egress and does not opt into residential fallback, so some pages may fail. Inspect the request receipt for compilation, repair and network charges. Changing a field's structure can affect extractor reuse; a wording change is not a reliable way to request a fresh operation.
Finally, test a representative set of permitted pages and manually compare important values. A wrong product's valid-looking price can satisfy the schema. Keep source URL, retrieval context and receipt with each capture, store rejected records separately, and investigate systematic failures before retrying. The CLI reads small captures into memory and uses ordinary JSON parsing; it is not a streaming importer or a duplicate-member detector. Production ingestion needs explicit size, transport, provenance and retry policies around these record checks.