6

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?

ThinkBonobo
  • 15,487
  • 9
  • 65
  • 80

2 Answers2

5

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())
ThinkBonobo
  • 15,487
  • 9
  • 65
  • 80
  • 1
    For me, I see a `Object of type bytes is not JSON serializable` error with this code alone. To resolve, you'll need to call `.decode("utf-8")` to the serialized object. – Ghan Jun 22 '20 at 18:35
  • maybe convert to a string first? – ThinkBonobo Mar 10 '22 at 22:15
0

You can use package thriftpy2. Hope the snippets below could help:

import thriftpy2.protocol.json as proto

json_data = proto.struct_to_json(thrift_data)

where you can replace json_data and thrift_data with your own variables.

Tengerye
  • 1,796
  • 1
  • 23
  • 46