Google Cloud监控client.list_time_series未返回JSON对象问题求助
解决Google Cloud Monitoring Python客户端TimeSeries对象无法JSON序列化的问题
你遇到的问题根源是:Google Cloud Python客户端库返回的TimeSeries对象是Protocol Buffers(protobuf)实例,不是原生Python字典或JSON格式。官方文档提到的JSON格式是针对REST API的直接响应,而Python SDK用了protobuf封装,所以直接print会输出proto的文本格式,用json.dump自然会报序列化错误。
下面给你两种可行的解决方法:
方法1:将proto对象转为字典后序列化JSON
利用protobuf对象内置的to_dict()方法,把TimeSeries实例转为Python字典,再用json模块处理:
from google.cloud import monitoring_v3 import time import json client = monitoring_v3.MetricServiceClient() project_name = f"projects/{project_id}" now = time.time() seconds = int(now) nanos = int((now - seconds) * 10**9) interval = monitoring_v3.TimeInterval( { "end_time": {"seconds": seconds, "nanos": nanos}, "start_time": {"seconds": (seconds - 1200), "nanos": nanos}, } ) results = client.list_time_series( request={ "name": project_name, "filter": 'metric.type = "compute.googleapis.com/instance/cpu/utilization"', "interval": interval, "view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL, } ) # 转为字典并保存到文件 output_data = [result.to_dict() for result in results] with open("monitoring_metrics.json", "w") as f: json.dump(output_data, f, indent=2) # 或者打印格式化的JSON for result in results: print(json.dumps(result.to_dict(), indent=2))
方法2:直接用protobuf的JSON转换工具
Google提供了专门的工具将proto对象转为标准JSON字符串,需要导入json_format模块:
from google.cloud import monitoring_v3 import time from google.protobuf import json_format client = monitoring_v3.MetricServiceClient() project_name = f"projects/{project_id}" now = time.time() seconds = int(now) nanos = int((now - seconds) * 10**9) interval = monitoring_v3.TimeInterval( { "end_time": {"seconds": seconds, "nanos": nanos}, "start_time": {"seconds": (seconds - 1200), "nanos": nanos}, } ) results = client.list_time_series( request={ "name": project_name, "filter": 'metric.type = "compute.googleapis.com/instance/cpu/utilization"', "interval": interval, "view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL, } ) # 保存到文件 with open("monitoring_metrics.json", "w") as f: for result in results: json_str = json_format.MessageToJson(result, indent=2) f.write(json_str + "\n") # 或者打印 for result in results: print(json_format.MessageToJson(result, indent=2))
补充说明
- 你之前看到的非标准JSON格式,其实是protobuf对象的文本表示形式,是
print(result)调用对象__str__方法输出的结果,并非真正的JSON。 - 两种方法都能生成标准JSON,方便后续处理或保存到文件,按需选择即可。
内容的提问来源于stack exchange,提问作者Dev Jain
相关产品推荐
相关产品推荐

