I'm querying BigQuery via google-cloud-python
as follows:
client = bigquery.Client()
query = """SELECT * FROM `{dataset}.{table}`
WHERE id=@id LIMIT 1""".format(dataset=dataset,
table=table)
param = ScalarQueryParameter('id', 'STRING', id)
query = client.run_sync_query(query, query_parameters=[param])
query.use_legacy_sql = False
query.timeout_ms = 1000
query.run()
assert query.complete
try:
results = query.rows[0]
except IndexError:
results = None
This returns data like:
[
"Tue, 11 Apr 2017 03:18:52 GMT",
"A132",
"United Kingdom",
[
{
"endDate": "2012-12-05",
"startDate": "2011-12-27",
"statusCode": "Terminated"
}
]
]
The repeated field has been converted to JSON. But I want the rest of the data to be converted to JSON as well. I could implement this myself by examining query.schema
but it seems like this should be in the library since it already happens for repeated elements.
How can I get BigQuery query results formatted as JSON using this library? Eg:
{
"timestamp": "Tue, 11 Apr 2017 03:18:52 GMT",
"id": "A132",
"country": "United Kingdom",
[
{
"endDate": "2012-12-05",
"startDate": "2011-12-27",
"statusCode": "Terminated"
}
]
}
As it turns out, the code is simple enough:
field_names = [f.name for f in query.schema]
try:
raw_results = query.rows[0]
zipped_results = zip(field_names, raw_results)
results = {x[0]: x[1] for x in zipped_results}
except IndexError:
results = None
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.