I've tried to convert a thrift object to json in python.
If I try to use json.dumps(thriftObj)
, it fails with the following:
TypeError: MyThriftObj(...) is not JSON serializable
I tried fixing it with a default function:
json.dumps(thriftObj, default=lambda x: x.__dict__)
This worked in some cases but in other cases I get the error:
AttributeError: 'DictProxy' object has no attribute '__dict__'
How do I convert a valid thrift object to json?
Serialization is the process of transforming objects of complex data types (custom-defined classes, object-relational mappers, datetime, etc.) to native data types so that they can then be easily converted to JSON notation.
It is a format that encodes the data in string format. JSON is language independent and because of that, it is used for storing or transferring data in files. The conversion of data from JSON object string is known as Serialization and its opposite string JSON object is known as Deserialization.
Thrift comes with a serialization library that you can use. Most of the documentation I found for this is in Java or other languages but the library does exist in python. See below for some code you can use:
from thrift.TSerialization import serialize
from thrift.protocol.TJSONProtocol import TSimpleJSONProtocolFactory
def thrift_to_json(thrift_object):
return serialize(thrift_object, protocol_factory=TSimpleJSONProtocolFactory())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With