将字符串转换为字典数组

2 投票
1 回答
3560 浏览
提问于 2025-04-18 08:03

我有一个这样的字符串:

"[{'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 个回答

9

你那里没有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'}]

撰写回答