如何获取Reflex框架中State的原始值以实现JSON序列化?
解决Reflex State值JSON序列化报错的方法
你遇到的TypeError: Object of type StringCastedVar is not JSON serializable报错,是因为直接访问StateA.value这类类属性时,拿到的是Reflex框架封装的变量对象,不是实际的原始值。
要获取State的原始值,访问其他State的属性时需要用self.get()方法,它会返回属性的实际值而非封装对象。修改你的confirm方法即可解决问题:
class StateA(rx.State): value: str = "Hello" class StateB(rx.State): value: str = "World" class ConfirmButton(rx.State): did_confirm: bool = False @rx.event def confirm(self): self.did_confirm = True import json with open("x.json", mode='w') as h: h.write(json.dumps({ "word1": self.get(StateA.value), # 使用self.get()获取原始值 "word2": self.get(StateB.value), }))
补充说明:如果是访问当前State自身的属性(比如ConfirmButton里的did_confirm),直接用self.属性名就能拿到原始值,不需要额外调用get()方法。
内容的提问来源于stack exchange,提问作者toobee
相关产品推荐
相关产品推荐

