如何在python中将thrift对象转换为Json?

2024-10-03 23:20:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在python中将thrift对象转换为json。在

如果我尝试使用json.dumps(thriftObj),则会出现以下错误:

TypeError: MyThriftObj(...) is not JSON serializable

我试着用默认函数修复它:

json.dumps(thriftObj, default=lambda x: x.__dict__)

这在某些情况下有效,但在其他情况下,我得到了错误: AttributeError: 'DictProxy' object has no attribute '__dict__'

如何将有效的thrift对象转换为json?在


Tags: 对象jsonis错误not情况thrift中将
1条回答
网友
1楼 · 发布于 2024-10-03 23:20:13

Thrift附带了一个可以使用的序列化库。我找到的大部分文档都是用Java或其他语言编写的,但是python中确实存在这个库。请参阅下面的代码,以获取您可以使用的代码:

from thrift.TSerialization import serialize
from thrift.protocol.TJSONProtocol import TSimpleJSONProtocolFactory

def thrift_to_json(thrift_object):
  return serialize(thrift_object, protocol_factory=TSimpleJSONProtocolFactory())

相关问题 更多 >