moved code up before error occurs to see if encoding to json correctly at least..