当ast正常工作时,json.loads()无法将此字符串列表转换为列表



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

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((转换的字符串列表,为什么它在这个字符串列表上不起作用?

字符串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))

最新更新