我有这样一条信息:
[{"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))
这是错误:
文件“server.py”,第 137 行,in insert_in_db result = literal_eval(value)
文件“/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py”,第 84 行,在 literal_eval return _convert(node_or_string)
文件“/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py”,第 57 行,在 _convert return list(map(_convert, node.elts))
文件“/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py”,第 62 行,在 _convert in zip(node.keys, node.values))
文件“/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py”,第 61 行,返回 dict((_convert(k), _convert(v)) for k, v
文件“/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py”,第 83 行,在 _convert 中 raise ValueError(‘malformed node or string: ’ + repr(node)) ValueError: malformed node or字符串:<_ast.Name object at 0x109baae48>
也许我错过了检查空值的中间步骤?我似乎在 eval line 137
上遇到了错误。我从下面提到的堆栈溢出评论中得到了使用 ast.literal_eval
的想法。
它更多的是数据问题而不是我处理它的方式吗?我对 Python 不是很熟悉,所以我很可能遗漏了一些东西。
原文由 unseen_damage 发布,翻译遵循 CC BY-SA 4.0 许可协议