我正在使用 python 客戶端庫檔案來列出云資產。我需要將該輸出移動到 csv 檔案中。但我不能。因為它顯示TypeError: Object of type Asset is not JSON serializable
我的代碼
`response = client.list_assets(
request={
"parent": project_resource,
"read_time": None,
"asset_types": ["compute.googleapis.com/Instance"],
"content_type": asset_v1.ContentType.RESOURCE,
"page_size": 50,
}
)
for asset in response:
print(asset)
df = json_normalize(asset)
df.to_csv('list.csv', sep=',', encoding='utf-8')`
我的輸出
`TypeError: Object of type Asset is not JSON serializable`
請幫助它。 我需要使用任何其他庫檔案來轉換為 csv 嗎??
uj5u.com熱心網友回復:
我懷疑Asset是協議緩沖區訊息,并且(這些類)不是 JSON 可序列化的。
注意確認這
Asset是一個協議緩沖區。該方法使用gRPC轉碼,見assets.list
您應該(!)能夠MessageToJSON在google.protobuf.json_format 中使用將 protobuf 訊息轉換為 JSON,然后您可以將其轉換為 CSV。該模塊還包括MessageToDict在這種情況下哪個可能(!?)更可取。
更新
顯然(!)谷歌已經改變了對 API 客戶端庫的 Protobuf 支持,并使用Proto Plus for Python。直到您提出問題我才知道這一點。現在的解決方案是(!):
for asset in resp:
j = asset_v1.Asset.to_json(asset)
而且,IIUC,因為你需要to_json的協議緩沖區中的訊息,你將在需要迭代resp,to_json每個(!?) asset,然后轉換成CSV之前重新組合。
注意您的代碼出現 (!?)
Asset在回應中創建每個作為單獨的 CSV 檔案 (list.csv) 時,我懷疑您真的想要序列化回應的assets屬性(串列Asset)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/386369.html
