有没有办法使用 Python 将 bigquery 返回的结果转换为 Json 格式?

Posted

技术标签:

【中文标题】有没有办法使用 Python 将 bigquery 返回的结果转换为 Json 格式?【英文标题】:Is there a way to convert results returned from bigquery to Json format using Python? 【发布时间】:2021-01-01 20:19:15 【问题描述】:

目前使用python从bigquery中拉取数据,得到结果后需要转成JSON格式。如何将结果转成JSON?

 query_job2 = client_bq.query(query)
    query_job2.result()
    rows = list(query_job2.result())  # Waits for query to finish
    response = dict()
    """
    Creating a nested dictionary with the tables as the keys and inside each respective table will hold cost as keys and
    have a list of values
    """
    for row in rows:
        table = get_table_name(str(row.query))
        start_time =int(row.start_time.timestamp())
        end_time =int(row.end_time.timestamp())

        if table in response:
            if row.cost in response[table]:
                response[table] = list(response[table])
                response[table].append((str(row.creation_time),start_time,end_time , row.cost, str(row.query)))
        else:
            response[table] = 
            response[table] = (str(row.creation_time), start_time,end_time, row.cost, str(row.query))

这是我正在使用的查询:

     with data AS (
       SELECT
       creation_time,
       total_bytes_processed,
       query
       FROM `project.region-us.INFORMATION_SCHEMA.JOBS_BY_PROJECT`
       where creation_time > TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL -60 SECOND)  AND job_type = "QUERY"
       Group BY creation_time,  job_id, total_bytes_processed, query
       ORDER BY total_bytes_processed DESC
)
select as value
  array_agg(struct( creation_time,
       regexp_extract(query, r'(?i)\sfrom\s+`?(?:[\w-]+\.)*([\w-]+\.[\w-]+)`?\s' ) as table,
       (total_bytes_processed/1099511627776) * 5 as cost,
       query) order by (total_bytes_processed/1099511627776) * 5  desc limit 1)[offset(0)]
from data
group by timestamp_trunc(creation_time, minute)
    """

【问题讨论】:

这个问题可以更好地表达。您在问如何将 pandas.DataFrame 格式化为 json。您可以通过调用 df.to_json(orient=....) 来实现。它与 BigQuery 无关,因为您可以等效地从 CSV 读取数据。 @gidutz 真的很有趣,我想也许我可以直接从查询或其他东西中获取结果,或者将 row.iterator 对象转换为字典或其他东西 【参考方案1】:

问题可以分为两部分:

    如何将数据从 Google BigQuery 读取到 Pandas。你可以找到答案here

    from google.cloud import bigquery
    
    client = bigquery.Client()
    query_sql = """SELECT col FROM `table`"""
    
    df = client.query(query_sql).to_dataframe()
    

    获取pandas对象中的数据后,可以使用to_json方法将其转换为json字符串:

    df.to_json(orient='index')
    

或者,您可以直接从 BigQuery 将数据导出为 JSON 文件,或者从 UI 中显示的here 或使用 python 客户端。

如果您需要使用 pandas 操作内存中的数据,第一种方法更好,第二种方法可以让您序列化数据以实现更大的规模。

【讨论】:

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

有没有办法使用python将Windows鼠标光标更改为自定义光标?

有没有办法将 csv 数据加载到雪花表中并报告每条记录是不是已成功加载? (使用 Python)

有没有办法将 Python 变量传递给 Javascript 而无需将其写入文件?

我有一个包含 .mat 格式文件的文件夹。有没有办法可以使用 python 将所有这些文件转换为 json? [复制]

有没有办法将字符串变量传递给 python .loc/.iloc?

有没有办法使用python发送和接收调制信号的信号?