You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用insert_rows_json向BigQuery插入JSON数据时遇字符拆分错误

问题原因与解决方法

问题原因

insert_rows_json 方法要求传入的是JSON对象(Python字典)组成的列表,如果错误地传入了JSON字符串(比如直接把json.dumps()生成的字符串作为参数),Python会将字符串视为可迭代对象,逐个遍历字符,导致每个字符被当作单独的行数据传入,从而触发"rows的json字段为无效值"的错误。

典型错误写法:

# 错误:直接传入JSON字符串
json_data = '[{"timestamp": "2024-01-01T00:00:00", "temp":25}, ...]'
table.insert_rows_json(json_data)

解决方法

方法1:直接传入Python字典列表(推荐)

不需要手动序列化JSON,直接构造Python字典组成的列表传入即可,insert_rows_json 内部会自动处理序列化:

# 正确示例:构造字典列表
weather_records = [
    {"timestamp": "2024-01-01T00:00:00", "temperature": 22.5, "humidity": 60},
    {"timestamp": "2024-01-01T01:00:00", "temperature": 21.8, "humidity": 62},
    {"timestamp": "2024-01-01T02:00:00", "temperature": 21.2, "humidity": 65}
]
table.insert_rows_json(weather_records)

方法2:先反序列化JSON字符串为对象列表

如果你的数据已经是JSON字符串格式,先用json.loads()将其转为Python对象列表,再传入方法:

import json

# 假设有现成的JSON字符串
json_str = '''
[
    {"timestamp": "2024-01-01T00:00:00", "temperature": 22.5, "humidity": 60},
    {"timestamp": "2024-01-01T01:00:00", "temperature": 21.8, "humidity": 62},
    {"timestamp": "2024-01-01T02:00:00", "temperature": 21.2, "humidity": 65}
]
'''
# 反序列化为字典列表
weather_records = json.loads(json_str)
table.insert_rows_json(weather_records)

注意事项

  • 即使只有一条记录,也必须放在列表中传入,不能直接传单个字典或字符串。
  • 确保每个字典的键与BigQuery表的字段名完全匹配(大小写敏感)。

内容的提问来源于stack exchange,提问作者Hamed Tamadon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:03:15