我有这样一条信息:
[{"city": "Beverly Hills", "state": "", "postal_code": "", "address": "Some Address", "country": "USA"}, {"city": "New York", "state": "NY", "postal_code": "", "address": "P.O. BOX 52404", "country": "USA"}]
当我执行 type()
时,它显示为 <class 'str'>
。
如何将字符串转换为Python 3中的字典列表?
我尝试过使用literal_eval
并得到了错误malformed node or string:
,因此我不确定最好的方法是什么。
编辑
这里有一个可以重现的示例:
mydata = {'programs': '["France"]', 'ids': '[]', 'citizenships': '[]', 'nationalities': '["FR"]', 'places_of_birth': '[]', 'dates_of_birth': '["1973-03-25"]', 'addresses': '[{"state": null, "postal_code": null, "address": null, "city": null, "country": "FR"}]'}
for key,value in mydata.items():
if type(value) is str:
result = literal_eval(value)
print("value 1: ", value)
print("value type 2:", type(value))
print("result 3: ", result)
print("result 4: ", type(result))
for item in result:
print("item in result 5:", item)
print("type of item in result 6:", type(item))
以下是错误提示信息:
File "server.py", line 137, in insert_in_db result = literal_eval(value)
File "/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py", line 84, in literal_eval return _convert(node_or_string)
File "/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py", line 57, in _convert return list(map(_convert, node.elts))
File "/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py", line 62, in _convert in zip(node.keys, node.values))
File "/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py", line 61, in return dict((_convert(k), _convert(v)) for k, v
File "/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py", line 83, in _convert raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: <_ast.Name object at 0x109baae48>
我可能漏掉了检查空值的步骤吗?我好像在 line 137
的 eval 上得到了错误。我从下面提到的 stack overflow 评论中得到使用 ast.literal_eval
的想法。
这更多是数据问题而不是我处理方式的问题吗?我对 Python 不是很熟悉,所以我很可能遗漏了一些东西。
literal_eval
可以处理你的字符串。 - Ilya V. Schuroveval
、ast.literal_eval
和json.loads
都可以在提供的字符串上正常工作,没有任何问题。 - jedwards