tojson bug fix + refactor