现在我也在寻找同样的问题。我发现的一种解决方法是在 json.dumps 中使用 CustomEncoder。这是一个示例:
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)
在json.dumps(data, cls=CustomEncoder)中使用上述编码器
这是迄今为止我提供的唯一解决方案。如果我找到更好的解决方案会更新它。
编辑:
找到解决方案。这是 New Encoder 类。
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)
谢谢。
已编辑:更新的解决方案。在 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))