You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:SQLite字符串转list of list of dicts方法

解决Python中将SQLite取出的字符串转为list of list of dicts的问题

我来帮你搞定这个转换问题!首先得理清你遇到的核心问题:你从SQLite拿到的字符串外层多了一对不必要的双引号,而且之前的处理方式踩了几个小坑,导致ast和json库都没发挥作用。

问题分析

  • 字符串格式冗余:你的原始字符串被额外的双引号包裹着(就是a = ""[[...]]""里的外层双引号),这会直接干扰解析逻辑。
  • json解析失败原因:字符串里的True是Python的布尔值写法,而JSON标准要求布尔值是小写的true,所以json.loads会直接报错。
  • ast使用错误:你之前尝试[ast.literal_eval(x) for x in a]是把整个字符串拆成单个字符去解析,这完全不符合逻辑,应该直接解析整个清理后的字符串。
  • 不必要的replace操作:你用replace("[[","[").replace("]]","]")去掉了外层的嵌套列表结构,但你的目标就是list of list of dicts,这步操作反而破坏了原本正确的结构。

正确解决方案

直接用ast.literal_eval就能完美解决,因为它能兼容Python的语法元素(比如True、None),步骤如下:

import ast

# 从SQLite取出的原始字符串
a = ""[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]""

# 1. 清理字符串:去掉外层多余的双引号
cleaned_str = a.strip('"')

# 2. 用ast.literal_eval直接解析整个字符串
result = ast.literal_eval(cleaned_str)

# 验证结果结构
print(type(result))          # 输出 <class 'list'>(外层列表)
print(type(result[0]))       # 输出 <class 'list'>(内层列表)
print(type(result[0][0]))    # 输出 <class 'dict'>(列表中的字典)

# 遍历查看所有字典内容
for inner_list in result:
    for plugin_dict in inner_list:
        print("--- 插件信息 ---")
        for key, value in plugin_dict.items():
            print(f"{key}: {value}")

可选JSON方案(不推荐)

如果一定要用json库,需要先把字符串里的True替换成JSON标准的true,再去掉外层双引号,代码如下:

import json

cleaned_str = a.strip('"').replace("True", "true")
result = json.loads(cleaned_str)

内容的提问来源于stack exchange,提问作者user11576444

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:13:03