How can I check whether a JSON number is an integer or a decimal value?
Quick answer
Python’s standard JSON decoder converts integer-form number tokens such as 7 to int and fractional-form tokens such as 7.0 to float by default. [S1] Check the decoded value with type(value) is int or type(value) is float to enforce an exact type; the exact int check also rejects booleans. Choose which types and fields are valid from your own schema.
The question, the details, the next step.
A practical checklist
Write down each field’s expected decoded type and whether it is required.
Use
type(value) is intwhen booleans must not count as integers.Use
type(value) is floatonly if your schema requires a fractional-form number to decode as a float.Test integer, fractional, boolean, missing, and numeric-string inputs against the intended rules.
Decide separately whether extra fields and numeric conversions are allowed.
A few more useful answers
Why not use `isinstance(value, int)` for an integer field?
Because Python’s bool is an integer subtype, isinstance(True, int) is true. Use type(value) is int when a boolean must be rejected. [S1]
Should `7.0` count as an integer because it has no fractional part?
That depends on your schema. The decoder produces a float for a fractional-form token such as 7.0, so an exact int check rejects it. [S1]
Does this example define a general JSON schema?
No. It illustrates checks for two fields only. The required fields, accepted types, and treatment of extra fields must be specified for your own data.
Sources
References used for this guide.
- [S1] Python 3.15 json — JSON encoder and decoder docs.python.org · Checked
