Better JSON encoding and code refactor.