python - 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() 转换的字符串列表,为什么它在这个字符串列表上不起作用?
解决方案
该字符串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))
推荐阅读
- javascript - 使用 javascript 覆盖 chrome 默认快捷方式
- mysql - MySQL 日期范围查询索引仅适用于有限范围
- reactjs - redux/react-testing-library 的初始状态对于下一个测试用例保持不变
- mongodb - 如何保持 Azure blob 存储和 Mongo db 之间的一致性
- sql-server-2008 - 如何在 SSMS 中连接到 Azure SQL DB
- javascript - 仅匹配正则表达式的一部分
- c - C 代码适用于本地设备,但不适用于 leetcode
- python - 将字符串附加到列表/字符串返回'None'或'AttributeError:'str'对象在python中没有属性'append''
- php - PHP:将带有单独行的数组作为值插入数据库
- c# - .NET Core 3.1 Windows 服务的 EventLog 源名称