Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Google-Ads API GoogleAdsRow to json?

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'>

like image 969
user912830823 Avatar asked Apr 01 '19 14:04

user912830823


2 Answers

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)
like image 89
Matthieu Avatar answered Sep 20 '22 15:09

Matthieu


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})
like image 41
scott_m Avatar answered Sep 20 '22 15:09

scott_m