I am using GCP's Python client APIs for listing cloud assets. I need to move that output to a CSV file. But I can't because it is showing
TypeError: Object of type Asset is not JSON serializable
My code
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')`
My output
TypeError: Object of type Asset is not JSON serializable
Do I need to use any other library files to convert to CSV?
I suspect
Assetis a protocol buffer message and (these classes are) not JSON serializable.You should (!) be able to useMessageToJSONin google.protobuf.json_format to convert the protobuf message into JSON that you can then convert to CSV. The module also includesMessageToDictwhich may (!?) be preferable in this case.Update
Apparently (!) Google has changed its Protobuf support with API Client Libraries and uses Proto Plus for Python. I did not know this until your question. The solution is now (!):
And, IIUC, because you need to
to_jsonthe protocol buffer messages, you will need to iterate overresp,to_jsoneach (!?)assetand then reassemble them before converting to CSV.