reflex-dev/reflex · error · TypeError
The keys and values of the object must be literal vars to ge
Error message
The keys and values of the object must be literal vars to get the JSON representation.
What it means
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.
Source
Thrown at packages/reflex-base/src/reflex_base/vars/object.py:457
+ " })"
)
def json(self) -> str:
"""Get the JSON representation of the object.
Returns:
The JSON representation of the object.
Raises:
TypeError: The keys and values of the object must be literal vars to get the JSON representation
"""
keys_and_values = []
for key, value in self._var_value.items():
key = LiteralVar.create(key)
value = LiteralVar.create(value)
if not isinstance(key, LiteralVar) or not isinstance(value, LiteralVar):
msg = "The keys and values of the object must be literal vars to get the JSON representation."
raise TypeError(msg)
keys_and_values.append(f"{key.json()}:{value.json()}")
return "{" + ", ".join(keys_and_values) + "}"
def __hash__(self) -> int:
"""Get the hash of the var.
Returns:
The hash of the var.
"""
return hash((type(self).__name__, self._js_expr))
@classmethod
def _get_all_var_data_without_creating_var(
cls,
value: Mapping,
) -> VarData | None:
"""Get all the var data without creating a var.
View on GitHub (pinned to 45b8ed5ab7)
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.
Example fix
# before
class State(rx.State):
conn: dict = {} # contains a database connection object
# after
class State(rx.State):
_conn: dict = {} # backend-only
conn_info: dict = {} # plain JSON data for frontend Defensive patterns
Strategy: validation
Validate before calling
import json
def json_safe(obj) -> bool:
try:
json.dumps(obj)
return True
except TypeError:
return False Type guard
import json
def is_json_serializable(v) -> bool:
try:
json.dumps(v)
return True
except (TypeError, ValueError):
return False Prevention
- Store only JSON-safe data in frontend state vars.
- Prefix server-only structures with '_'.
- Register serializers for custom types once at app startup.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- Array elements must be of type LiteralVar, not {type(element
- The component `{child_name}` can only be a child of the comp
- Cannot serialize color that contains non-literal vars.
- Color is not a valid color.
- No valid JSON representation for {self}
AI-assisted analysis of reflex-dev/reflex@45b8ed5ab7 (2026-08-28).
Data as JSON: /api/errors/011dd4b4bcd8c336.
Report an issue: GitHub.