使用singlestoredb读取SingleStore JSON列时JSONDecodeError求助
解决singlestoredb读取JSON列时因列位置引发的JSONDecodeError
问题背景
使用Python的singlestoredb库读取SingleStore数据库的JSON列时,若SELECT语句中将JSON列(如output)放在列列表中间,会抛出json.decoder.JSONDecodeError: Extra data异常;但将该列移至列表末尾时,脚本可正常运行。
已知条件:
output列存储合法的大JSON数据,列定义为'output' JSON COLLATE utf8mb4_general_ci DEFAULT NULL,数据长度约137KB- 已尝试调整编码、转换数据类型等方法,无效
临时解决方案
方案1:查询时强制将JSON列转为字符串
在SQL语句中用CAST将JSON列转为字符串,避免singlestoredb库自动解析时出错,之后在Python中手动解析JSON:
import singlestoredb as s2 import pandas as pd import json query = """ select uuid ,CAST(output AS CHAR) AS output ,environment from table_name where uuid = 'aaa' and environment = 'live' """ conn = s2.connect( user = "your_user", password = "your_pass", host = "your_host", port = "your_port", database = "your_db", results_type='dict', charset='utf8mb4' ) with conn.cursor() as cur: cur.execute(query) rows = cur.fetchall() # 手动解析JSON for row in rows: if row['output']: row['output'] = json.loads(row['output']) df = pd.DataFrame(rows) print(df)
方案2:禁用自动JSON解析(改用元组结果)
将连接的results_type改为tuple,避免库自动解析JSON字段,之后手动映射列名并解析:
import singlestoredb as s2 import pandas as pd import json query = """ select uuid ,output ,environment from table_name where uuid = 'aaa' and environment = 'live' """ conn = s2.connect( user = "your_user", password = "your_pass", host = "your_host", port = "your_port", database = "your_db", results_type='tuple', # 改用元组结果,不自动解析JSON charset='utf8mb4' ) with conn.cursor() as cur: cur.execute(query) # 获取列名 columns = [col[0] for col in cur.description] # 转换为字典并解析JSON rows = [] for row_tuple in cur.fetchall(): row_dict = dict(zip(columns, row_tuple)) if row_dict['output']: row_dict['output'] = json.loads(row_dict['output']) rows.append(row_dict) df = pd.DataFrame(rows) print(df)
原因推测
这大概率是singlestoredb库的缓冲区处理bug:当JSON列(大字段)位于结果集中间时,库在读取数据时未正确分割不同列的边界,导致后续列的部分数据被拼接到JSON字符串末尾,触发JSON解析的"Extra data"错误;而将JSON列放在末尾时,没有后续数据,因此解析正常。
永久修复建议
若临时方案无法满足需求,建议到singlestoredb的官方代码仓库提交issue,提供你的环境信息(Python版本、singlestoredb版本、SingleStore版本)、复现代码及异常日志,帮助开发者定位并修复该bug。
内容的提问来源于stack exchange,提问作者Anand
相关产品推荐
相关产品推荐

