【问题标题】:Incompatible types while writing JSON to BigQuery table将 JSON 写入 BigQuery 表时类型不兼容
【发布时间】:2021-12-28 17:59:53
【问题描述】:

我有一个从 API 服务器接收 JSON 数据并将其上传到具有指定架构的 BigQuery 表的函数。 JSON 数据有一些字段应该是 STRING 但只包含数字。这是一个json数据的示例:

{
"realizationreport_id":5200242,
"suppliercontract_code":null,
"rrd_id":4681869162,
"gi_id":3246258,
"subject_name":"\xd0\x9a\xd0\xb0\xd0\xbb\xd1\x8c\xd1\x81\xd0\xbe\xd0\xbd\xd1\x8b",
"nm_id":44185221,          <--- serialized to INTEGER but should be STRING
"barcode":"2010739265043"  <--- serialized to INTEGER but should be STRING
........
}

表架构:

      bigquery.SchemaField("realizationreport_id", "INTEGER", mode="NULLABLE"),
      bigquery.SchemaField("suppliercontract_code", "STRING", mode="NULLABLE"),
      bigquery.SchemaField("rrd_id", "INTEGER", mode="REQUIRED"),
      bigquery.SchemaField("gi_id", "INTEGER", mode="NULLABLE"),
      bigquery.SchemaField("subject_name", "STRING", mode="NULLABLE"),
      bigquery.SchemaField("nm_id", "STRING", mode="NULLABLE"), #integer
      bigquery.SchemaField("barcode", "STRING", mode="NULLABLE"),#integer
      ...................

上传到表格

job_config = bigquery.LoadJobConfig(
                schema = wb_options.get_schema(),                
                autodetect = False
                )

loadJob = client.load_table_from_json(json_result, table, job_config=job_config)  
loadJob.result()

当 JSON 开始转储数据时,它满足 STRING 表字段的 INTEGER 值

JSON parsing error in row starting at position 0: Could not convert value to string. Field: nm_id; Value: 44185221

如何将 nm_id 等特定字段的 json 解码函数更改为 STRING?

我是否应该通过添加元数据映射{default : CustomDecode} json.dumps(metadata).encode("utf-8") 以某种方式做到这一点。

或者bigquery.LoadJobConfig中有需要的功能?

【问题讨论】:

  • 在示例 json 数据中,条形码有双引号,而 nm_id 没有。是否适合您的用例,能够在输入 json 中将 nm_id 用双引号括起来,以便 bigquery 将其视为字符串?
  • barcode 和 nm_id 的行为相同,它们都转换为 NUMBER。所以我猜双引号将无济于事:((根据API服务的文档,此字段设置为STRING。
  • JSON 定义将字段视为数字,您要求一个字符串,它失败了。在字段值周围添加双引号以将其转换为 JSON 中的字符串,或更改您的 BigQUery 架构以接受数字。
  • 没错。但我需要更改将整数字段解码为字符串的行为。我不知道为什么它应该是字符串,也许是出于未来的原因。 JSON定义考虑双引号值,只有数字为INTEGER
  • @gawkface 谢谢!似乎我必须更改 BigQuery 架构并密切关注这个问题

标签: google-bigquery google-cloud-functions jsondecoder


【解决方案1】:

从 BigQuery Python API 的 LoadJobConfig reference 中,我找不到任何可以完全满足您需要的功能。 decimal_target_types 很有趣,但是当我测试时,它不能在请求中提供表模式的同时使用。当使用documentation guide 手动将 JSON 整数设置为字符串时,它可以正常工作,适合表模式。我认为要走的路是编辑 JSON 解码函数以自动将相关属性转换为字符串,正如 other thread 所探讨的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多