将字符串转换为字典数组

时间:2014-05-30 11:34:49

标签: 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"

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

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

1 个答案:

答案 0 :(得分:6)

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

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

import ast

obj = ast.literal_eval(datastring)

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'}]