Nelson's log

On JSON and nothingness

Python’s JSON module serializes the Python value None as the JSON value null. This is correct. However it causes odd bugs if you are not aware of it.

Specifically, I had code like this:

db.execute('insert into table values(?)', json.dumps(foo.get("bar"))

I was trying to insert a database NULL if foo didn’t have the key “bar”. But foo.get() returns None, which gets turned into the string “null”, which results in the string ‘null’ being inserted into the column. Derp.

>>> json.dumps(None)
>>> json.loads('null') == None
>>> json.dumps('null')
>>> json.loads('"null"')

>>> json.loads(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/json/", line 312, in loads
TypeError: the JSON object must be str, not 'NoneType'