JSON Schema: Why You Get 'must be number' and How to Fix It for Good
"must be number", "must be string" or "should be number": the 4 real causes of Ajv type errors, how to find the field via instancePath, and where to fix it.
The payload arrived. The JSON parses without error. The schema is declared. And yet Ajv returns must be number for a field that clearly contains a number. The first reaction is to suspect the schema. The second is to suspect the validator. Neither is right.
The must be number error is not a validator bug: it is the validator doing its job, rejecting a value that arrived as the string "150" where the contract asks for the number 150. The problem lies with whoever produced the data, and it is almost always one of the same four sources. This post reproduces each one with Ajv 8, covers the other messages in the same family (must be string, must be integer, the old should be number), shows how to find the field through instancePath, and where to fix it. Setting up Ajv itself (allErrors, formats, compiling the schema) is covered in JSON Schema in Practice: Validate Before Processing.
The 4 causes of the "must be number" error
Every example below ran with Ajv 8.20 against a schema with "amount": { "type": "number" }.
1. HTML forms
An HTML <form> never sends JSON. The only enctype values are application/x-www-form-urlencoded (the default), multipart/form-data and text/plain (MDN), and in all of them fields travel as text. JSON only exists when some JavaScript builds the body — and the most common shortcut for that, Object.fromEntries(new FormData(form)), keeps everything as strings:
Object.fromEntries(new URLSearchParams('amount=150&qty=2&active=true'));
// { amount: '150', qty: '2', active: 'true' }
// Ajv: /amount must be number, /qty must be integer, /active must be boolean
input type="number" doesn't change that: the value it hands to FormData is still a string.
2. APIs that serialize numbers as strings
Many systems return monetary values as strings, "amount": "150.00", sometimes to preserve decimal precision, sometimes by accident. If you validate a third-party API response against your own schema, this is the most likely cause.
3. Database drivers that return DECIMAL as a string
In Node, this is the cause that shows up most, and it doesn't depend on "database configuration": it is the default behavior of the two most used drivers. I tested against PostgreSQL 16 and MySQL 8.4 in Docker:
pg(node-postgres 8.23):select 150.00::numeric(10,2)comes back as'150.00'. The driver returns every type that has no registered parser as a string (types documentation), andNUMERICis one of them;BIGINTalso comes back as a string, and thepg-typesREADME explains why: a JavaScriptnumbercan't hold 64 bits without risking a changed value.mysql2(3.24): aDECIMAL(10,2)column comes back as'150.00', in bothqueryandexecute, unless the connection is created withdecimalNumbers: true.
The data is correct in the database. Serialization changed the type.
4. Environment variables
process.env.RATE_LIMIT is always a string, even with RATE_LIMIT=100 in .env. The same goes for os.getenv() in Python and getenv() in PHP (prefer getenv() over $_ENV, which is empty when php.ini's variables_order doesn't include E, as in php.ini-production). A schema that validates configuration read from the environment fails on every numeric field nobody converted.
Other messages from the same error
must be number is just one member of the family. They all have keyword: "type" and the expected type in params.type:
| Message (Ajv 8) | Typical cause |
|---|---|
must be number |
number arriving as a string (the 4 causes above) |
must be integer |
"2" instead of 2, or 1.5 in an integer field |
must be string |
numeric id where the contract asks for a string (ZIP code, phone) |
must be boolean |
"true"/"on" from a checkbox or query string |
must be object |
object serialized twice ("{\"a\":1}") |
must be array |
a single value where a list was expected (tags=node) |
must be null |
empty string "" in a field declared only as null |
If the message you see is should be number, the project uses Ajv 6 or earlier. The v8 migration guide records both changes: "should" became "must" in messages, and dataPath became instancePath. The cause and the fix are the same; old Stack Overflow answers saying "should be" still apply.
When the error is a missing field rather than a wrong type, the message is different (must have required property), and it has its own traps with null and empty strings: see JSON Schema required: What It Actually Validates.
How to read the instancePath to find the culprit field
Ajv returns an array of errors with this structure:
{
"instancePath": "/items/0/price",
"schemaPath": "#/properties/items/items/properties/price/type",
"keyword": "type",
"params": { "type": "number" },
"message": "must be number"
}
instancePath is a JSON Pointer: /items/0/price means the price field of the first element (index 0) of the items array. Empty ("") means the error is at the root. schemaPath points to the rule that failed in the schema, useful when there is a $ref or allOf along the way.
Turn on allErrors: true. Without it Ajv stops at the first error, and you fix one field at a time, rerunning after every attempt.
number vs integer
"type": "number" accepts any JSON number: 1, 1.5, -42. It does not accept the string "1". "type": "integer" accepts only numbers with no fractional part, and there is a version gotcha here: since draft-06, 1.0 counts as an integer, because the type is defined as "any number with a zero fractional part". In draft-04, integer was "a JSON number without a fraction or exponent part", so 1.0 did not pass (draft-06 release notes). In JavaScript you never see this, because JSON.parse("1.0") already returns 1; it shows up in validators in other languages that still use draft-04.
The classic mistake is using integer for a monetary value with cents: 19.99 is rejected. Either the field is number, or the value is represented as integer cents, the decision the REST API JSON Schema walkthrough adopts.
Fix it at the edge, with code
The right fix is converting the type where data enters the system: in the form handler, in the third-party API adapter, in the driver configuration. Three examples I tested:
// Form / query string: convert field by field, without hiding garbage
function toNumber(value) {
if (typeof value !== 'string' || value.trim() === '') return value; // let the schema complain
const n = Number(value);
return Number.isFinite(n) ? n : value;
}
const raw = Object.fromEntries(new FormData(form));
const input = { ...raw, amount: toNumber(raw.amount), qty: toNumber(raw.qty) };
The empty-string check isn't pedantry: Number('') returns 0, so a field left blank would silently become zero. With the toNumber above, "" and "abc" stay strings and Ajv reports must be number, which is what you want.
// node-postgres: register a parser for NUMERIC (OID 1700)
import pg from 'pg';
pg.types.setTypeParser(1700, (v) => parseFloat(v));
// mysql2: DECIMAL as number
const conn = await mysql.createConnection({ ...config, decimalNumbers: true });
The last two trade precision for convenience: parseFloat on a large NUMERIC or one with many decimal places loses digits. For money, the honest alternative is keeping a string in the schema (next section) or working with integer cents. Validating at the entry point, before anything is written, is the subject of How to Validate Data Before Saving It to the Database.
coerceTypes: the shortcut that becomes technical debt
Ajv has the coerceTypes option (documentation), off by default. With coerceTypes: true, the string "150" passes as number and Ajv mutates the object to 150. I tested the limits:
- only a valid numeric string is converted:
"abc"still givesmust be number, and"1e3"becomes1000; - an empty string does not become
0in anumberfield (the docs say""is only coerced tonull); "true"and"false"become booleans;"on"does not;- with
coerceTypes: "array", a single value is wrapped in an array ("node"becomes["node"]) and a one-element array is unwrapped when the schema asks for a scalar.
Coercion makes sense where everything is a string by definition and you control the schema: query strings and environment variables. Anywhere else, it masks the broken producer. The schema now "says" the field is a number while, on any code path that doesn't go through this validator, it keeps arriving as a string.
When a numeric string is a design decision
Sometimes you don't control the producer: the third-party API returns "amount": "150.00" and won't change. Then the schema should reflect reality:
{
"amount": {
"type": "string",
"pattern": "^-?[0-9]+(\\.[0-9]+)?$"
}
}
Or, if the field varies between API versions:
{
"amount": {
"oneOf": [
{ "type": "number" },
{ "type": "string", "pattern": "^-?[0-9]+(\\.[0-9]+)?$" }
]
}
}
Document that this is a concession to the producer. A union of number and numeric string in a system you control end to end is a sign that one side isn't honoring the contract. And if the numeric string produces the wrong type in your front-end TypeScript, generate the interfaces from a real payload with the JSON to TypeScript converter: it shows right away which fields are arriving as string.
Frequently asked questions
What is the difference between number and integer in JSON Schema?
number accepts any number, with or without decimals. integer accepts only numbers with a zero fractional part; since draft-06 that includes 1.0. Neither accepts a string, so "10" fails both.
How do I translate Ajv's error messages?
Use the ajv-i18n package: after validating, call the localizer for your language on validate.errors (for example localize['pt-BR'](validate.errors) turns must be number into "deve ser um número"). For your own per-field messages, ajv-errors adds an errorMessage keyword to the schema (it requires allErrors: true).
Why do some tutorials show "should be number"?
Because they were written for Ajv 6 or earlier. Ajv 8 replaced "should" with "must" in messages and renamed dataPath to instancePath. The cause of the error and the fix didn't change.
Can I just turn on coerceTypes and move on?
You can, if the input is a string by nature (query string, environment variable) and you know Ajv will mutate the validated object. For an API's JSON payload, prefer fixing the producer or converting at the edge; coercion hides the problem instead of solving it.
Fix the producer, not the validator
must be number has a consistent root cause: something on the data's path produced the wrong type — a form, an API that serializes numbers as strings, a driver that returns DECIMAL as text, an environment variable nobody converted. Read the instancePath, trace where the field came from, and convert the type at the entry point, not in the validator. To reproduce the error before touching code, paste the payload and the schema into the JSON Schema Validator: it runs Ajv with allErrors on and shows the instancePath, the failing keyword and the message for each error.
- 01 CPU Cores vs. Threads: What Actually Changes in Practice Understand the difference between CPU cores and threads and what actually changes for performance, multitasking, gaming, and development.
- 02 MIT, Apache, and GPL Licenses: Practical Differences for Developers MIT, Apache 2.0, and GPL are not the same thing. Understand permissive vs copyleft, patent protection, and compatibility before shipping code to production.