如何使用 Python 将 bigquery 返回的结果转换为 Json 格式?

Posted

技术标签:

【中文标题】如何使用 Python 将 bigquery 返回的结果转换为 Json 格式?【英文标题】:How to convert results returned from bigquery to Json format using Python? 【发布时间】:2019-09-04 23:09:18 【问题描述】:

使用 Python 从 Bigquery 公共数据集中选择数据,得到结果后需要以 JSON 格式打印。如何将结果转换为 JSON?谢谢!

已尝试row[0],但出现错误。

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

# from google.cloud import bigquery
# client = bigquery.Client()

query = """
    SELECT word, word_count
    FROM `bigquery-public-data.samples.shakespeare`
    WHERE corpus = @corpus
    AND word_count >= @min_word_count
    ORDER BY word_count DESC;
"""
query_params = [
    bigquery.ScalarQueryParameter("corpus", "STRING", "romeoandjuliet"),
    bigquery.ScalarQueryParameter("min_word_count", "INT64", 250),
]
job_config = bigquery.QueryJobConfig()
job_config.query_parameters = query_params
query_job = client.query(
    query,
    # Location must match that of the dataset(s) referenced in the 
    query.location="US",
    job_config=job_config,
)  # API request - starts the query

# Print the results
for row in query_job:
    print(": \t".format(row.word, row.word_count))
assert query_job.state == "DONE"

【问题讨论】:

【参考方案1】:

您实际上可以让 BigQuery 直接生成 JSON。像这样更改您的查询:

query = """
SELECT TO_JSON_STRING(word, word_count) AS json
FROM `bigquery-public-data.samples.shakespeare`
WHERE corpus = @corpus
AND word_count >= @min_word_count
ORDER BY word_count DESC;
"""

现在结果将有一个名为 json 的列,并带有 JSON 格式的输出。

【讨论】:

【参考方案2】:

目前没有自动转换的方法,但是有一个非常简单的手动转换成json的方法:

records = [dict(row) for row in query_job]
json_obj = json.dumps(str(records))

另一种选择是使用 pandas 进行转换:

df = query_job.to_dataframe()
json_obj = df.to_json(orient='records')

【讨论】:

以上是关于如何使用 Python 将 bigquery 返回的结果转换为 Json 格式?的主要内容,如果未能解决你的问题,请参考以下文章