【问题标题】:json.loads() cannot convert this string list to a list while ast works properlyjson.loads() 在 ast 正常工作时无法将此字符串列表转换为列表
【发布时间】:2020-10-30 07:29:52
【问题描述】:

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

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

【问题讨论】:

  • 这不是有效的 JSON。 ast.literal_eval 解析 Python 语法的一个子集; json.loads 解析 JSON。没有理由期望两者之间有任何联系。

标签: python python-3.x string list


【解决方案1】:

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

【讨论】:

  • 非常感谢!我会多注意引号XD
猜你喜欢
  • 2018-08-10
  • 2014-05-23
  • 2014-11-03
  • 2013-06-09
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 2011-02-08
相关资源
最近更新 更多