Right now I am also looking for the same problem. One workaround that I have found is that use a CustomEncoder in json.dumps. Here is a sample:
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (google.protobuf.wrappers_pb2.StringValue,
google.protobuf.wrappers_pb2.Int64Value,
google.protobuf.wrappers_pb2.DoubleValue)):
return obj.value
elif isinstance(obj, google.protobuf.pyext._message.RepeatedCompositeContainer):
data = []
try:
while True:
item = obj.pop()
data.append(self.default(item))
except IndexError:
return data
elif isinstance(obj, google.ads.google_ads.v1.proto.common.custom_parameter_pb2.CustomParameter):
return {
self.default(obj.key): self.default(obj.value)
}
return json.JSONEncoder.default(self, obj)
Use the above encoder in json.dumps(data, cls=CustomEncoder)
This is the only solution I have so far come with. Will update it if I find a better solution.
Edited:
Found the Solution. Here is the New Encoder class.
class GoogleProtoEncoder(json.JSONEncoder):
"""
Custom JSON Encoder for GoogleAdsRow.
Usage: json.dumps(data, cls=GoogleProtoEncoder)
"""
def default(self, obj):
"""
Overriden method. When json.dumps() is called, it actually calls this method if
this class is specified as the encoder in json.dumps().
"""
if isinstance(obj, google.protobuf.message.Message) and hasattr(obj, 'value'):
# This covers native data types such as string, int, float etc
return obj.value
elif isinstance(obj, google.protobuf.pyext._message.RepeatedCompositeContainer):
# This is basically for python list and tuples
data = []
try:
while True:
item = obj.pop()
data.append(self.default(item))
except IndexError:
return data
elif isinstance(obj, google.ads.google_ads.v1.proto.common.custom_parameter_pb2.CustomParameter):
# Equivalent to python dictionary
return {
self.default(obj.key): self.default(obj.value)
}
elif isinstance(obj, google.protobuf.message.Message):
# All the other wrapper objects which can have different fields.
return {key[0].name: getattr(obj, key[0].name) for key in obj.ListFields()}
return json.JSONEncoder.default(self, obj)
Thanks.
Edited: Updated solution. Works in V7
import proto
response = ga_service.search_stream(search_request)
for batch in response:
for row in batch.results:
logging.debug(proto.Message.to_dict(row))