GCP BigQuery加载含嵌套引号的CSV数据失败问题排查
问题:BigQuery读取带转义引号的CSV失败,是否必须预先格式化?
问题详情
待读取的CSV数据
id, xml 1, "{\"field1\": 1234, \"field2\": \"some string with a comma,\"}" 2, "{\"field1\": 5678, \"field3\": \"some string without a comma\"}"
尝试的BigQuery CSVOptions配置
format="CSV" allow_quoted_newlines=true quote='\"' skip_leading_rows=1
报错信息
Data between close quote character (") and field separator.;
line_number: 2 byte_offset_to_start_of_line: 40 column_index: 1 column_name: "xml" column_type: STRING value: "{\" File: gs://my-bucket.myfile.csv"
已尝试设置不同的quote值:'"'、'\"',甚至'\\\"'(但因不是单个字符失败),想问是否必须先格式化CSV才能加载到BigQuery?
解决办法
不用预先格式化CSV,问题核心是转义规则不匹配:
BigQuery的CSV解析默认遵循RFC 4180标准,内部引号需要用**两个连续双引号("")**转义,而不是你CSV里用的反斜杠转义(\")。针对这个情况有两个可行方案:
方案1:调整CSV的转义格式
把CSV里所有的\"替换成"",修改后的CSV如下:
id, xml 1, "{""field1"": 1234, ""field2"": ""some string with a comma,""}" 2, "{""field1"": 5678, ""field3"": ""some string without a comma""}"
然后设置quote='"',其余参数不变,就能正常读取。
方案2:改用JSON格式读取
因为你的xml字段本身就是JSON结构,直接把文件当成JSONL(每行一个JSON对象)处理更简单,完全避开CSV的引号问题。修改后的文件内容如下:
{"id":1, "xml": {"field1": 1234, "field2": "some string with a comma,"}} {"id":2, "xml": {"field1": 5678, "field3": "some string without a comma"}}
然后将CSVOptions换成format="JSON",即可顺利加载数据。
内容的提问来源于stack exchange,提问作者swygerts
相关产品推荐
相关产品推荐

