使用Python将BigQuery模式表转换成JSON

4

我需要一个 Python 版本的 BigQuery 等效函数 bq show --format=prettyjson myproject:mydataset.mytable

是否有一种方法可以在 Python 中使用 BigQuery API 来完成?

我在 Python 中尝试了以下内容:

view_ref = self._client.dataset(dataset.dataset_id).table(table.table_id)
table_obj = self._client.get_table(view_ref)

dict_schema = []
for schema_field in table_obj.schema:
    dict_schema.append({
        'name': schema_field.name,
        'mode': schema_field.mode,
        'type': schema_field.field_type
   })

它几乎能够工作;我只是缺少嵌套模式字段。

感谢回复,祝您有美好的一天。

1个回答

12
您可以使用schema_to_json()方法轻松将表模式转换为JSON格式。该方法需要两个属性:分别是 schema_listdestination
我使用一个带有嵌套数据的公共数据集来说明您的情况,并使用StringIO()仅仅是为了展示模式。
from google.cloud import bigquery
import io

client = bigquery.Client()

project = 'bigquery-public-data'
dataset_id = 'samples'
table_id = 'shakespeare'

dataset_ref = client.dataset(dataset_id, project=project)
table_ref = dataset_ref.table(table_id)
table = client.get_table(table_ref)


f = io.StringIO("")
client.schema_to_json(table.schema, f)
print(f.getvalue())

输出结果:

[
  {
    "description": "A single unique word (where whitespace is the delimiter) extracted from a corpus.",
    "mode": "REQUIRED",
    "name": "word",
    "type": "STRING"
  },
  {
    "description": "The number of times this word appears in this corpus.",
    "mode": "REQUIRED",
    "name": "word_count",
    "type": "INTEGER"
  },
  {
    "description": "The work from which this word was extracted.",
    "mode": "REQUIRED",
    "name": "corpus",
    "type": "STRING"
  },
  {
    "description": "The year in which this corpus was published.",
    "mode": "REQUIRED",
    "name": "corpus_date",
    "type": "INTEGER"
  }
]

当使用命令!bq show --format=prettyjson bigquery-public-data:samples.wikipedia | jq '.schema.fields'时,输出的结果与以下内容相同:


出现了mypy错误:在“Client”的“schema_to_json”的第2个参数中,类型为“StringIO”不兼容;期望的是“Union[str,bytes,PathLike[str],PathLike[bytes]]”类型。有什么建议如何修复? - Alex M
client.schema_to_json(table.schema, f) 属性错误:'TableListItem'对象没有属性'schema' - Viknesh S K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接