uns*_*age 0 python string dictionary list python-3.x
我有一条信息如下:
[{"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"}]
Run Code Online (Sandbox Code Playgroud)
当我这样做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))
Run Code Online (Sandbox Code Playgroud)
这是错误:
在insert_in_db中的文件"server.py",第137行result = literal_eval(value)
文件"/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py",第84行,在literal_eval中返回_convert( node_or_string)
文件"/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py",第57行,在_convert返回列表中(map(_convert,node.elts))
文件"/ Users/user/anaconda3/envs/apicaller/lib/python3.5/ast.py",第62行,在zip中的_convert(node.keys,node.values)中)
文件"/ Users/user/anaconda3/envs/apicaller/lib/python3 .5/ast.py",第61行,返回dict((_ convert(k),_ convert(v))for k,v
File"/Users/user/anaconda3/envs/apicaller/lib/python3.5/ast .py",第83行,在_convert中引发ValueError('格式错误的节点或字符串:'+ repr(node))ValueError:格式错误的节点或字符串:<_ast.Name object at 0x109baae48>
也许我错过了检查空值的步骤?我好像在eval上得到了错误line 137.我有想法使用ast.literal_eval下面提到的堆栈溢出注释.
这是一个数据问题而不是我处理它的方式吗?我对Python不太熟悉,所以我很可能会遗漏一些东西.
import json
data = json.loads(<your_string>)
Run Code Online (Sandbox Code Playgroud)
小智 6
我知道我回答得很晚,但希望对其他人有帮助:
您可以使用: pip install pyyaml import yaml
x = '[{"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"}]'
x = yaml.load(x)
Run Code Online (Sandbox Code Playgroud)
现在字符串已转换为字典列表。