先给结论,这种问题不要设置你源对象(视你使用的脚本语言不同可能有些差别)中的缺省值为空,直接不传即可
问题描述:写脚本时碰到的问题,脚本语言:python3,使用库:pymysql,json,requests,re,time,BeautifulSoup
大致代码逻辑如下(省去一些具体逻辑):
res = []
for i in temp: //
// 一些逻辑,下面开始正则匹配
for pattern in patterns:
if pattern[1].match(i[2]):
// 一些逻辑
res.append({
'speech_id':pattern[0],
'speech':speech[pattern[0]-1],
'chinese_meaning':i[3]
})
break
// 没有匹配到,将某些字段置为空,加入目标数组
res.append({
'speech_id':'',
'speech':'',
'chinese_meaning':i[3]
})
// 更多逻辑
若匹配到结果则返回,若无匹配项则设置某些项为空字符串
解决方法:移除python对象中对缺省值的设置
res = []
for i in temp:
// 一些逻辑,下面开始正则匹配
for pattern in patterns:
if pattern[1].match(i[2]):
// 一些逻辑
res.append({
'speech_id':pattern[0],
'speech':speech[pattern[0]-1],
'chinese_meaning':i[3]
})
break
// 没有匹配到,将某些字段置为空,加入目标数组
res.append({
'chinese_meaning':i[3]
})
// 更多逻辑
原因
看第一篇文章https://dba.stackexchange.com/questions/220748/mysql-temp-table-insert-from-json-cant-handle-null-values,主要的复现代码如下:
DROP TABLE IF EXISTS t1;
CREATE TABLE t1 (
id BIGINT PRIMARY KEY,
c1 BIGINT AS (c2->>"$.c1") STORED NULL,
c2 JSON, INDEX(c1));
mysql> INSERT INTO t2 (id, c2) VALUES (1, '{"c1": null}');
ERROR 3156 (22018): Invalid JSON value for CAST to INTEGER from column json_extract at row 1
mysql> INSERT INTO t2 (id, c2) VALUES (1, '{"c1": 1}');
Query OK, 1 row affected (0.01 sec)
可以看出这是一个与生成列(generated column)相关的问题,c1是依赖于c2生成的,猜测mysql内部对这个JSON进行了CAST操作,而报错就在设置c2的c1字段为空的时候发生。
第二篇文章https://dba.stackexchange.com/questions/220748/mysql-temp-table-insert-from-json-cant-handle-null-values对这种现象进行了进一步阐释(猜测):
主要是你在object中定义的空值会被转换为BAD NULL,具体如下:
{"item":1,"quantity":4} --> item = 1, quantity = 4
{"item":1,"quantity":null} --> item = 1, quantity = 'null' ( Some kind of unfriendly json null )
{"item":1} --> item = 1, quantity = NULL ( Your good old sql null ! )
可以看到第三串才是我们想要的那种,也是sql能够转换的那种
参考:
https://bugs.mysql.com/bug.php?id=88033
https://dba.stackexchange.com/questions/220748/mysql-temp-table-insert-from-json-cant-handle-null-values