您基本上必须遵循有关如何使用load json data using python 的文档,使用nested and repeated fields。例如,使用后一个链接中的模式,您可以通过以下方式加载嵌套和重复的 JSON 数据(您可以使用找到的示例数据进行测试 here):
import sys
def load_nested_json():
from google.cloud import bigquery
client = bigquery.Client()
dataset_id, table_id, uri = sys.argv[1:]
dataset_ref = client.dataset(dataset_id)
job_config = bigquery.LoadJobConfig()
job_config.schema = [
bigquery.SchemaField('id', 'STRING', mode='NULLABLE'),
bigquery.SchemaField('first_name', 'STRING', mode='NULLABLE'),
bigquery.SchemaField('last_name', 'STRING', mode='NULLABLE'),
bigquery.SchemaField('dob', 'DATE', mode='NULLABLE'),
bigquery.SchemaField('addresses', 'RECORD', mode='REPEATED', fields=[
bigquery.SchemaField('status', 'STRING', mode='NULLABLE'),
bigquery.SchemaField('address', 'STRING', mode='NULLABLE'),
bigquery.SchemaField('city', 'STRING', mode='NULLABLE'),
bigquery.SchemaField('state', 'STRING', mode='NULLABLE'),
bigquery.SchemaField('zip', 'STRING', mode='NULLABLE'),
bigquery.SchemaField('numberOfYears', 'STRING', mode='NULLABLE'),
]),
]
table_ref = dataset_ref.table(table_id)
# Uncomment following lines to also create the destination table
# table = bigquery.Table(table_ref, job_config.schema)
# table = client.create_table(table)
# print('Created table {}'.format(table.full_table_id))
job_config.source_format = "NEWLINE_DELIMITED_JSON"
load_job = client.load_table_from_uri(
uri,
table_ref,
job_config=job_config) # API request
assert load_job.job_type == 'load'
load_job.result() # Waits for table load to complete.
assert load_job.state == 'DONE'
if __name__ == '__main__':
load_nested_json()