Refactoring and rewriting the as_json method