add better checking for nulls and JSON elements

refactor code
check for presence of elements before trying to read values