ThinkBonobo
ThinkBonobo

Reputation: 16515

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

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?

Upvotes: 6

Views: 6901

Answers (2)

Tengerye
Tengerye

Reputation: 1964

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.

Upvotes: 1

ThinkBonobo
ThinkBonobo

Reputation: 16515

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())

Upvotes: 5

Related Questions