How to get json representation from search_all_iam_policies() results

I'm working to implement the search_all_iam_policies() method in google-cloud-asset as follows:

from google.cloud import asset_v1
ASSET_CLIENT = asset_v1.AssetServiceClient()
response = ASSET_CLIENT.search_all_iam_policies(
  scope='projects/my_project',
  query='[email protected]'
)
policies = []
for policy in response:
  policies.append(policy)
return json.dumps({
  'policies': policies
})

But cannot find a way to get JSON representation of policies nor policy. In this case 'response' is a google.cloud.asset_v1.services.asset_service.pagers.SearchAllIamPoliciesPager and each 'policy' is an google.cloud.asset_v1.types.assets.IamPolicySearchResult. I can print them to the console but need them in JSON format to send to another system.


Solution 1:

Just to expand on Michaels answer. When using that approach you "lose" some information namely the resource, project, asset_type and organization.

from google.cloud import asset_v1
from google.protobuf.json_format import MessageToJson

ASSET_CLIENT = asset_v1.AssetServiceClient()
response = ASSET_CLIENT.search_all_iam_policies(
  scope='projects/my_project',
  query='[email protected]' # This field is optional
)
policies = []
for policy in response:
    policies.append(
        {
            "resource": f"{policy.resource}",
            "project": f"{policy.project}",
            "bindings": json.loads(MessageToJson(policy.policy)).get('bindings'),
            "asset_type": f"{policy.asset_type}",
            "organization": f"{policy.organization}"
        }
    )

This will give you a list of dicts that look like the following:

{
  'resource': '//some_resource',
  'project': 'some_project',
  'bindings': [
    {
      'role': 'some_role',
      'members': [
        'projectEditor:some_project',
        'projectOwner:some_project'
      ]
    },
    {
      'role': 'some_other_role',
      'members': [
        'projectViewer:some_project'
      ]
    },
  ],
  'asset_type': 'some_asset_type',
  'organization': 'some_organization'
}