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

如何将JSON中字符串形式的列表转为Python列表?

解决方法

方法1:使用ast.literal_eval()(推荐)

ast.literal_eval()可以安全解析Python字面量(列表、字典等格式),完美适配你这种单引号包裹的字符串列表,且不会像eval()存在安全风险。

示例代码:

import ast

jsonresp = {
    "number":1,
    "size":17,
    "totalPages":1,
    "numberOfElement":17,
    "totalElements":"17",
    "accounts":"['123', '456', '789']"
}

accounts_list = ast.literal_eval(jsonresp["accounts"])
print(type(accounts_list))  # 输出: <class 'list'>
print(accounts_list)        # 输出: ['123', '456', '789']

方法2:替换引号后用json.loads()

JSON规范要求字符串用双引号,因此可以先将字符串中的单引号替换为双引号,再用json模块解析:

示例代码:

import json

jsonresp = {
    "number":1,
    "size":17,
    "totalPages":1,
    "numberOfElement":17,
    "totalElements":"17",
    "accounts":"['123', '456', '789']"
}

# 替换单引号为双引号
accounts_str = jsonresp["accounts"].replace("'", "\"")
accounts_list = json.loads(accounts_str)
print(type(accounts_list))  # 输出: <class 'list'>
print(accounts_list)        # 输出: ['123', '456', '789']

为什么list(jsonresp["accounts"])无效?

list()函数会把传入的字符串逐个字符拆分为列表元素,比如原字符串"['123', '456', '789']"会被拆成['[', "'", '1', '2', '3', "'", ',', ' ', "'", '4', '5', '6', "'", ',', ' ', "'", '7', '8', '9', "'", ']'],这显然不是你需要的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:15:39