我有一条信息是这样的:[{"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()时,它显示为。
如何在Python3中将此信息从字符串获取到字典列表?
我试过literal_eval但得到了一个错误,所以我不确定最好的方法是什么
编辑
下面是一个应该可以重复的例子: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>
也许我遗漏了检查空值的中间步骤?我似乎得到了evalline 137上的错误。我从下面提到的堆栈溢出注释中得到了使用ast.literal_eval的想法。
这是不是更多的数据问题,而不是我处理它的方式?我对Python不太熟悉,所以很可能遗漏了一些东西。