【问题标题】:Unable to save list of dict data with cx_Oracle LOB object to a JSON file无法将带有 cx_Oracle LOB 对象的 dict 数据列表保存到 JSON 文件
【发布时间】:2020-06-24 09:50:19
【问题描述】:

我有一个通过 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】:

    从 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 或更小),但您似乎已经做出了这种假设。

    【讨论】:

      猜你喜欢
      • 2015-12-14
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 2021-12-21
      • 2017-09-10
      • 2018-06-09
      • 2013-07-10
      • 1970-01-01
      相关资源
      最近更新 更多