首页 > 解决方案 > json.loads() 在 ast 正常工作时无法将此字符串列表转换为列表

问题描述

我在下面有一个字符串列表我想变成一个列表

import json
import ast    
s = "['https://i.ebayimg.com/images/g/PWMAAOSw4MdfmPuu/s-l1000.jpg', 'https://i.ebayimg.com/images/g/mFwAAOSw-8xfPMyu/s-l1000.jpg', 'https://i.ebayimg.com/images/g/inUAAOSwIftfPMyx/s-l1000.jpg', 'https://i.ebayimg.com/images/g/8WcAAOSw~dxfPMy~/s-l1000.jpg', 'https://i.ebayimg.com/images/g/lRAAAOSwqSBfPMy9/s-l1000.jpg', 'https://i.ebayimg.com/images/g/1akAAOSwQJBfPMzB/s-l1000.jpg', 'https://i.ebayimg.com/images/g/EQYAAOSwPZNfPMzE/s-l1000.jpg', 'https://i.ebayimg.com/images/g/YfAAAOSwQDFfPMzR/s-l1000.jpg', 'https://i.ebayimg.com/images/g/rqwAAOSwCoJfPMzP/s-l1000.jpg', 'https://i.ebayimg.com/images/g/fJcAAOSwn9VfPMzT/s-l1000.jpg', 'https://i.ebayimg.com/images/g/QN8AAOSwfo1fPMzV/s-l1000.jpg', 'https://i.ebayimg.com/images/g/KusAAOSwYEdfPMze/s-l1000.jpg', 'https://i.ebayimg.com/images/g/lIMAAOSw2rNfPMzb/s-l1000.jpg', 'https://i.ebayimg.com/images/g/rKYAAOSwHKZfPMzg/s-l1000.jpg', 'https://i.ebayimg.com/images/g/krgAAOSwpAZfPMzh/s-l1000.jpg']"
    m = json.loads(s)

虽然 json.loads() 给出错误,但 ast 工作正常

import json
import ast
s = "['https://i.ebayimg.com/images/g/PWMAAOSw4MdfmPuu/s-l1000.jpg', 'https://i.ebayimg.com/images/g/mFwAAOSw-8xfPMyu/s-l1000.jpg', 'https://i.ebayimg.com/images/g/inUAAOSwIftfPMyx/s-l1000.jpg', 'https://i.ebayimg.com/images/g/8WcAAOSw~dxfPMy~/s-l1000.jpg', 'https://i.ebayimg.com/images/g/lRAAAOSwqSBfPMy9/s-l1000.jpg', 'https://i.ebayimg.com/images/g/1akAAOSwQJBfPMzB/s-l1000.jpg', 'https://i.ebayimg.com/images/g/EQYAAOSwPZNfPMzE/s-l1000.jpg', 'https://i.ebayimg.com/images/g/YfAAAOSwQDFfPMzR/s-l1000.jpg', 'https://i.ebayimg.com/images/g/rqwAAOSwCoJfPMzP/s-l1000.jpg', 'https://i.ebayimg.com/images/g/fJcAAOSwn9VfPMzT/s-l1000.jpg', 'https://i.ebayimg.com/images/g/QN8AAOSwfo1fPMzV/s-l1000.jpg', 'https://i.ebayimg.com/images/g/KusAAOSwYEdfPMze/s-l1000.jpg', 'https://i.ebayimg.com/images/g/lIMAAOSw2rNfPMzb/s-l1000.jpg', 'https://i.ebayimg.com/images/g/rKYAAOSwHKZfPMzg/s-l1000.jpg', 'https://i.ebayimg.com/images/g/krgAAOSwpAZfPMzh/s-l1000.jpg']"

m=ast.literal_eval(s)

print(type(m))
print(m)

但是我曾经成功地使用 json.loads() 转换的字符串列表,为什么它在这个字符串列表上不起作用?

标签: pythonpython-3.xstringlist

解决方案


该字符串s不是有效的 JSON。JSON 标准不允许字符串使用单引号。

您可以修改代码以用双引号替换单引号,它会正常工作。

import json 

s = '["https://i.ebayimg.com/images/g/PWMAAOSw4MdfmPuu/s-l1000.jpg", "https://i.ebayimg.com/images/g/mFwAAOSw-8xfPMyu/s-l1000.jpg"]'
print(json.loads(s))

推荐阅读