将字符串转换为字典数组

nis*_*ish -1 python json python-2.7

我有一个以下形式的字符串:

"[{'status': 'Unshipped', 'city': 'New Delhi', 'buyer_name': 'xxx', 'name': 'xxx', 'countryCode': 'IN', 'payment_method': 'COD', 'y_id': 'xxx', 'phone': 'xxx', 'state': 'New Delhi', 'service': 'Expedited', 'amout': '425.00', 'address_1': 'xxx', 'address_2': 'xxx', 'postalCode': '110018', 'shipped_by_y': 'false', 'channel': 'MFN', 'order_type': 'StandardOrder'}, {'status': 'Unshipped', 'city': 'thane', 'buyer_name': 'xxx', 'name': 'xxx', 'countryCode': 'IN', 'payment_method': 'COD', 'y_id': 'xxx', 'phone': 'xxx', 'state': 'Maharashtra', 'service': 'Expedited', 'amout': '350.00', 'address_1': 'xxx', 'address_2': 'xxx', 'postalCode': '400607', 'shipped_by_y': 'false', 'channel': 'MFN', 'order_type': 'StandardOrder'}]\n"
Run Code Online (Sandbox Code Playgroud)

如何将此字符串转换为相应字典的数组.

我试图将字符串转换为JSON,然后加载JSON.但它仍然是一个字符串.

Mar*_*ers 6

那里没有JSON; 看起来你直接将带有字典的Python列表转换为字符串.

使用ast.literal_eval()将其转换回Python对象:

import ast

obj = ast.literal_eval(datastring)
Run Code Online (Sandbox Code Playgroud)

ast.literal_eval()将解析限制为仅对象文字(元组,列表,字典,字符串,数字),避免全面eval()调用带来的任意代码执行风险.

演示:

>>> import ast
>>> datastring = "[{'status': 'Unshipped', 'city': 'New Delhi', 'buyer_name': 'xxx', 'name': 'xxx', 'countryCode': 'IN', 'payment_method': 'COD', 'y_id': 'xxx', 'phone': 'xxx', 'state': 'New Delhi', 'service': 'Expedited', 'amout': '425.00', 'address_1': 'xxx', 'address_2': 'xxx', 'postalCode': '110018', 'shipped_by_y': 'false', 'channel': 'MFN', 'order_type': 'StandardOrder'}, {'status': 'Unshipped', 'city': 'thane', 'buyer_name': 'xxx', 'name': 'xxx', 'countryCode': 'IN', 'payment_method': 'COD', 'y_id': 'xxx', 'phone': 'xxx', 'state': 'Maharashtra', 'service': 'Expedited', 'amout': '350.00', 'address_1': 'xxx', 'address_2': 'xxx', 'postalCode': '400607', 'shipped_by_y': 'false', 'channel': 'MFN', 'order_type': 'StandardOrder'}]\n"
>>> ast.literal_eval(datastring)
[{'status': 'Unshipped', 'city': 'New Delhi', 'buyer_name': 'xxx', 'name': 'xxx', 'countryCode': 'IN', 'payment_method': 'COD', 'shipped_by_y': 'false', 'phone': 'xxx', 'state': 'New Delhi', 'service': 'Expedited', 'address_1': 'xxx', 'address_2': 'xxx', 'postalCode': '110018', 'order_type': 'StandardOrder', 'amout': '425.00', 'channel': 'MFN', 'y_id': 'xxx'}, {'status': 'Unshipped', 'city': 'thane', 'buyer_name': 'xxx', 'name': 'xxx', 'countryCode': 'IN', 'payment_method': 'COD', 'shipped_by_y': 'false', 'phone': 'xxx', 'state': 'Maharashtra', 'service': 'Expedited', 'address_1': 'xxx', 'address_2': 'xxx', 'postalCode': '400607', 'order_type': 'StandardOrder', 'amout': '350.00', 'channel': 'MFN', 'y_id': 'xxx'}]
Run Code Online (Sandbox Code Playgroud)