Im querying google ads api and need to save results as json. What is the best way to convert GoogleAdsRow type into json?
The result of the google ads appi look like this (the campaign and customer ids are fake):
campaign {
resource_name: "customers/752830100/campaigns/22837002"
id {
value: 22837002
}
name {
value: "test"
}
}
metrics {
clicks {
value: 51
}
impressions {
value: 33
}
}
type = <class 'google.ads.googleads_v1.types.GoogleAdsRow'>
Google.protobuf has a method called json_format which can do exactly that. Below is a code example to help:
# Import the method
from google.protobuf import json_format
import json
# Query the Ads API,
ga_service = client.get_service('GoogleAdsService', version='YOUR_VERSION')
query = ('YOUR_QUERY')
# Response as an iterator made up of GoogleAdsRow
response = ga_service.search(customer_id, query)
# Converting each of the GoogleAdsRow to json
for row in response :
json_str = json_format.MessageToJson(row)
d = json.loads(json_str)
If you don't have to use the SDK, another option to get the json, is to query the API sending a post request directly, which returns a json response:
r = requests.post('https://googleads.googleapis.com/v3/customers/YOUR_CUSTOMER_ID/googleAds:searchStream',
headers={'Authorization': f'Bearer {access_token}',
'developer-token' : developer_token,
'login-customer-id' : 'YOUR_CUSTOMER_ID',
'Content-Type': 'application/json'},
params={"query" : query})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With