python - 将 JSON 上传到 Bigquery 未特定错误
问题描述
在短暂尝试(https://github.com/pydata/pandas- gbq ) 并意识到 pandas-gbq 不支持 RECORD 类型,即没有嵌套字段。
现在我正在尝试将嵌套数据上传到 BigQuery。我设法使用相应的模式创建了表,但是我正在努力上传 json 数据。
from google.cloud import bigquery
from google.cloud.bigquery import Dataset
from google.cloud.bigquery import LoadJobConfig
from google.cloud.bigquery import SchemaField
SCHEMA = [
SchemaField('full_name', 'STRING', mode='required'),
SchemaField('age', 'INTEGER', mode='required'),
SchemaField('address', 'RECORD', mode='REPEATED', fields=(
SchemaField('test', 'STRING', mode='NULLABLE'),
SchemaField('second','STRING', mode='NULLABLE')
))
]
table_ref = client.dataset('TestApartments').table('Test2')
table = bigquery.Table(table_ref, schema=SCHEMA)
table = client.create_table(table)
当尝试将一个非常简单的 JSON 上传到 bigquery 时,我得到一个相当模糊的错误
400 Error while reading data, error message: JSON表遇到太多错误,放弃。行数:1;错误: 1. 请查看错误流以获取更多详细信息。
除了它放弃我让我有点难过之外:),显然错误描述并没有真正帮助......请在下面找到我如何尝试上传 JSON 和示例数据。
job_config = bigquery.LoadJobConfig()
job_config.source_format = bigquery.SourceFormat.NEWLINE_DELIMITED_JSON
with open('testjson.json', 'rb') as source_file:
job = client.load_table_from_file(
source_file,
table_ref,
location='US', # Must match the destination dataset location.
job_config=job_config) # API request
job.result() # Waits for table load to complete.
print('Loaded {} rows into {}:{}.'.format(
job.output_rows, dataset_id, table_id))
这是我的 JSON 对象
“[{'full_name':'test','age':2,'address':[{'test':'hi','second':'hi2'}]}]”
JSON 示例会很棒,因为如果我没记错的话,这似乎是上传嵌套数据的唯一方法。
解决方案
我一直在使用相同的代码和您共享的 JSON 内容重现您的场景,我怀疑问题只是您在引号("
或'
)之间定义 JSON 内容,而它不应该具有这种格式。
正确的格式是@ElliottBrossard 在他的回答中已经与您分享的格式:
{'full_name':'test', 'age':2, 'address': [{'test':'hi', 'second':'hi2'}]}
如果我使用文件中的内容运行您的代码testjson.json
,我会收到响应Loaded 1 rows into MY_DATASET:MY_TABLE
并且内容会加载到表中。否则,如果我使用下面的格式(您根据您的问题和其他答案中的评论使用该格式),我会得到结果google.api_core.exceptions.BadRequest: 400 Error while reading data, error message: JSON table encountered too many errors, giving up. Rows: 1; errors: 1. Please look into the error stream for more details
。
"{'full_name':'test','age':2,'address':[{'test':'hi','second':'hi2'}]}"
此外,您可以转到 BigQuery UI 中的“作业”页面(通过链接https://bigquery.cloud.google.com/jobs/YOUR_PROJECT_ID),在那里您将找到有关失败的加载作业的更多信息。例如,当我使用错误的 JSON 格式运行您的代码时,我得到的是:
正如您将看到的,这里的错误消息更相关:
error message: JSON parsing error in row starting at position 0: Value encountered without start of object
它表明它找不到任何有效的 JSON 对象{
的开头(即对象开头的括号)。
TL;DR:删除 JSON 对象中的引号,加载作业应该没问题。
推荐阅读
- docker - 当处于未就绪状态时保持 Kubernetes Pod 处于服务状态
- c++ - 'mutex' 未在此范围内声明。使用 MinGW 编译器处理 VS 代码
- r - 用逗号分隔的字符串总数
- swift - swift中的减号(无法读取数据)
- python - 如何使用 python 在 MS Word 中创建/修改动态目录
- javascript - gulp version.match -> 无法读取属性“匹配”
- java - 如何使用多线程来创建 gremlin 边缘
- aframe - A-frame 'look-at' 组件可以查看默认相机吗?
- r - Julia 循环和 R 循环一样慢
- asp.net - 将多个数据集传递给视图 [MVC]