Correctly check for null values and don't try to access non existing keys

Fixes #544