【问题标题】:How to serialize list of list of sets to json for insert into DB column如何将集合列表的列表序列化为 json 以插入 DB 列
【发布时间】:2020-03-23 13:40:58
【问题描述】:

我有一个嵌套的列表列表(这是一个嵌套的 Python 集)

def = [
    ['and', 'exp', 'a', {'1','2','3'}], 
    ['and', 'exp', 'b', {'4'}], 
    ['and_not', 'exp', 'c', {'5','6','7'}], 
    ['and_not', 'exp', 'd', {'8','9'}]
]

我正在尝试将其序列化为要插入到 SQL Server 表中的 json。

无法确定列表的深度,但它始终包含集合。

我目前正在使用的代码 -

str_def = json.dumps(str(def)).encode('utf-8')

表中的列是 varbinary(max) 数据类型

cmd = "insert into dummy_table(def) values (str_def)"

我收到两个错误 - 一个是集合无法序列化为 json,另一个是在插入表时 - 即使我将数据转换为二进制格式,如何处理单引号。

【问题讨论】:

  • 您使用的是 MYSQL 数据库吗?另外,您是否要转义引号?

标签: python json sql-server


【解决方案1】:

您可以在列表中转换您的集合:

my_def = [
    ['and', 'exp', 'a', {'1','2','3'}], 
    ['and', 'exp', 'b', {'4'}], 
    ['and_not', 'exp', 'c', {'5','6','7'}], 
    ['and_not', 'exp', 'd', {'8','9'}]
]

json_ready = [[list(e) if isinstance(e, set) else e for e in l] for l in my_def]

json.dumps(json_ready).encode('utf-8')

输出:

b'[["and", "exp", "a", ["2", "1", "3"]], ["and", "exp", "b", ["4"]], ["and_not", "exp", "c", ["5", "6", "7"]], ["and_not", "exp", "d", ["9", "8"]]]'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-25
    • 2020-04-05
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    相关资源
    最近更新 更多