{"record":{"id":"011dd4b4bcd8c336","repo":"reflex-dev/reflex","slug":"the-keys-and-values-of-the-object-must-be-literal","errorCode":null,"errorMessage":"The keys and values of the object must be literal vars to get the JSON representation.","messagePattern":"The keys and values of the object must be literal vars to get the JSON representation\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"packages/reflex-base/src/reflex_base/vars/object.py","lineNumber":457,"sourceCode":"            + \" })\"\n        )\n\n    def json(self) -> str:\n        \"\"\"Get the JSON representation of the object.\n\n        Returns:\n            The JSON representation of the object.\n\n        Raises:\n            TypeError: The keys and values of the object must be literal vars to get the JSON representation\n        \"\"\"\n        keys_and_values = []\n        for key, value in self._var_value.items():\n            key = LiteralVar.create(key)\n            value = LiteralVar.create(value)\n            if not isinstance(key, LiteralVar) or not isinstance(value, LiteralVar):\n                msg = \"The keys and values of the object must be literal vars to get the JSON representation.\"\n                raise TypeError(msg)\n            keys_and_values.append(f\"{key.json()}:{value.json()}\")\n        return \"{\" + \", \".join(keys_and_values) + \"}\"\n\n    def __hash__(self) -> int:\n        \"\"\"Get the hash of the var.\n\n        Returns:\n            The hash of the var.\n        \"\"\"\n        return hash((type(self).__name__, self._js_expr))\n\n    @classmethod\n    def _get_all_var_data_without_creating_var(\n        cls,\n        value: Mapping,\n    ) -> VarData | None:\n        \"\"\"Get all the var data without creating a var.\n","sourceCodeStart":439,"sourceCodeEnd":475,"githubUrl":"https://github.com/reflex-dev/reflex/blob/45b8ed5ab735f8a56bbb09a42384f030eb0208e7/packages/reflex-base/src/reflex_base/vars/object.py#L439-L475","documentation":"LiteralObjectVar.json() builds the JS object literal by converting each key and value with LiteralVar.create. If any key or value cannot become a LiteralVar (e.g. contains non-serializable objects like sockets, locks, arbitrary class instances), TypeError is raised because no static JS representation exists.","triggerScenarios":"Storing a dict in state containing non-serializable values (datetime with custom tz, open files, ORM sessions, arbitrary objects) and rendering it or serializing state to the frontend.","commonSituations":"Putting unserializable objects in state vars that get hydrated to the client; @rx.var computed vars returning dicts holding custom class instances; migrating state fields from backend to frontend without cleaning contents.","solutions":["Make the var a backend var (prefix with '_') if the client doesn't need it.","Add a serializer for the offending type via reflex's serializer registry (register a function that converts it to JSON-safe data).","Convert values to plain JSON types (str/dict/list) before storing them in state."],"exampleFix":"# before\nclass State(rx.State):\n    conn: dict = {}  # contains a database connection object\n\n# after\nclass State(rx.State):\n    _conn: dict = {}  # backend-only\n    conn_info: dict = {}  # plain JSON data for frontend","handlingStrategy":"validation","validationCode":"import json\n\ndef json_safe(obj) -> bool:\n    try:\n        json.dumps(obj)\n        return True\n    except TypeError:\n        return False","typeGuard":"import json\n\ndef is_json_serializable(v) -> bool:\n    try:\n        json.dumps(v)\n        return True\n    except (TypeError, ValueError):\n        return False","tryCatchPattern":null,"preventionTips":["Store only JSON-safe data in frontend state vars.","Prefix server-only structures with '_'.","Register serializers for custom types once at app startup."],"tags":["reflex","literal-var","serialization","objectvar"],"backgroundTag":"var-unserializable-to-json","analyzedSha":"45b8ed5ab735f8a56bbb09a42384f030eb0208e7","analyzedAt":"2026-08-28T19:25:27.644Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}