Skip to main content
 首页 » 编程设计

python之将字符串转换为字典列表 Python 3

2025年05月04日20zengkefu

我有这样一条信息:

[{"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>

也许我错过了检查空值的中间步骤?我似乎在 eval line 137 上遇到了错误.我想到了使用 ast.literal_eval来自下面提到的堆栈溢出评论。

与其我处理它的方式相比,它更像是一个数据问题吗?我对 Python 不是很熟悉,所以我很可能遗漏了一些东西。

请您参考如下方法:

import json 
 
data = json.loads(<your_string>)