无法将带有cx_Oracle LOB对象的字典数据列表保存到JSON文件中

问题描述 投票:0回答:1

我有一个通过cx_oracle库运行的选择查询。此查询的输出存储为dict列表,需要将其保存在json文件中,以备将来使用和迭代。

但是此查询的输出具有“ cx_oracleLOB对象”,因此,我陷入了错误“ TypeError:LOB类型的对象不可JSON序列化”,并且无法写入json文件。请找到我的代码:

con = cx_Oracle.connect(***)
cursor = con.cursor()
cursor.execute(q)

col_names = [row[0] for row in cursor.description]
rv = cursor.fetchall()
json_data = []
for result in rv:
    json_data.append(dict(zip(col_names, result)))
with open("result.json",'w')as fp:
     fp.write(json.dumps(json_data))

sample output of selectquery:

[
  {
    "name": "abc",
    "age": 10,
    "skills": <cx_Oracle.LOBobjectat0x00000123>
  },
  {
    "name": "def",
    "age": 10,
    "skills": <cx_Oracle.LOBobjectat0x000004456>
  }
]

json blob python-3.6 cx-oracle
1个回答
0
投票

从cx_Oracle文档Fetching LOBs as Strings and Bytes,创建输出类型处理程序:

def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
    if defaultType == cx_Oracle.CLOB:
        return cursor.var(cx_Oracle.LONG_STRING, arraysize=cursor.arraysize)
    if defaultType == cx_Oracle.BLOB:
        return cursor.var(cx_Oracle.LONG_BINARY, arraysize=cursor.arraysize)

这是假定您的LOB可以容纳在内存中(并且每个大小都在1 Gb或更小),但是您似乎已经在进行这种假设。

© www.soinside.com 2019 - 2024. All rights reserved.