Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert a thrift object to Json in python?

Tags:

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?

like image 409
ThinkBonobo Avatar asked Sep 19 '19 18:09

ThinkBonobo


People also ask

What is JSON serialization in python?

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.

What is JSON serialization and deserialization in Python?

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.


1 Answers

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())
like image 125
ThinkBonobo Avatar answered Sep 21 '22 16:09

ThinkBonobo