Files and data

Validate required fields in a JSON record

After parsing JSON, validate the fields your application actually needs. Check the container type, required properties, and permitted value ranges before starting a transformation.

Worked example

Node.js example · save as example.mjs and run node example.mjs

function validRow(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value)
    && typeof value.id === "string" && value.id.length > 0
    && Number.isInteger(value.count) && value.count >= 0;
}
console.log(validRow({id: "item-1", count: 0}));
console.log(validRow({id: "item-1", count: "0"}));

How it works

The checks encode a small explicit schema: an object with a nonempty string ID and a nonnegative integer count. Rejecting a string count avoids silently choosing a coercion policy. Additional unknown properties remain allowed in this particular contract.

Limits and mistakes

Hand-written validation becomes harder to maintain for deeply nested or evolving schemas. Use a suitable schema validator when the structure warrants it. This check does not impose a maximum count or normalize IDs; add those requirements only if the domain needs them.

Check the result

Expect true and false. Include null, arrays, missing fields, negative counts, and blank IDs. Confirm the error report points to the failed field in the actual importer.

Sources

Reference documentation for the behavior used in this guide: