Qia*_*mei 4 python json google-bigquery
使用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"
Run Code Online (Sandbox Code Playgroud)
Meo*_*eow 18
目前没有自动转换的方法,但是有一个非常简单的手动转换为 json 的方法:
records = [dict(row) for row in query_job]
json_obj = json.dumps(str(records))
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用熊猫进行转换:
df = query_job.to_dataframe()
json_obj = df.to_json(orient='records')
Run Code Online (Sandbox Code Playgroud)
您实际上可以直接让 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;
"""
Run Code Online (Sandbox Code Playgroud)
现在结果将有一个json以 JSON 格式输出命名的列。