How can I distinguish a missing JSON key from a key set to null?
Quick answer
After Python decodes JSON, an object becomes a dictionary and JSON null becomes Python None. Check "field" in record first. If the key is present, record["field"] is None tells you its value is null. If it is absent, membership is false. Avoid using record.get("field") is None alone: get() also returns None by default when the key is missing. [S1] [S2]
The question, the details, the next step.
A practical checklist
Decode the JSON into a Python dictionary.
Check
"field" in recordto test whether the key exists.If the key exists, check
record["field"] is Nonefor JSONnull.Handle the remaining present, non-null value according to your needs.
Do not use
record.get("field") is Nonealone when missing and null must differ.
A few more useful answers
What happens if I use `record["field"]` when the key is missing?
Dictionary subscription with a missing key raises KeyError. Check membership first if you need to handle absence without that exception. [S2]
Can I use a custom default with `get()` instead?
Yes. A unique sentinel can distinguish a missing key from a stored None, but membership followed by inspection is often easier to read when you need separate branches.
Does this check validate the whole JSON object?
No. It distinguishes key absence from a present null value; it does not validate a schema or establish that other keys or values are acceptable.
Sources
References used for this guide.
- [S1] json — JSON encoder and decoder — Python 3.15.2 documentation docs.python.org · Checked
- [S2] Python Tutorial: Data Structures — Dictionaries docs.python.org · Checked
