在 Python 中,我如何转换一个看起来像这样的字符串对象
"{
apartment=false,
walls=[{min_height=18, max_height=3, color=WHITE}],
appliances=[{type=[oven, washing_machine, microwave, drying_machine,
dish_washer, television]}],
rooms=[{bathroom=true, floor=2}, {bedroom=true, floor=[2,3], needs_renovation=EXCLUDE}],
value=[{sale_price=9003.01, occupied=true, family_unit=UNKNOWN}]
}"
像这样的字典对象?
{
"apartment": False,
"walls": [{"min_height": 18, "max_height": 3, "color": "WHITE"}],
"appliances": [{"type": ["oven", "washing_machine", "microwave", "drying_machine",
"dish_washer", "television"]}],
"rooms": [{"bathroom": True, "floor": 2}, {"bedroom": True, "floor":[2,3], "needs_renovation": "EXCLUDE"}],
"value": [{"sale_price": 9003.01, "occupied": True, "family_unit": "UNKNOWN"}]
}
我正在使用 Simple way to convert a string to a dictionary , 但它并没有让我走得足够远,因为我无法处理嵌套的字典和列表。
请您参考如下方法:
使用正则表达式和普通字符串替换,以及 json 包:
import json
from pprint import pprint
string = '''{
apartment=false,
walls=[{min_height=18, max_height=3, color=WHITE}],
appliances=[{type=[oven, washing_machine, microwave, drying_machine,
dish_washer, television]}],
rooms=[{bathroom=true, floor=2}, {bedroom=true, floor=[2,3], needs_renovation=EXCLUDE}],
value=[{sale_price=9003.01, occupied=true, family_unit=UNKNOWN}]
}'''
processed = re.sub(r'([A-Za-z_]+)', r'"\1"', string.replace('\n', '')).replace('=', ':').replace('"true"', 'true').replace('"false"', 'false')
pprint(json.loads(processed))
输出:
{'apartment': False,
'appliances': [{'type': ['oven',
'washing_machine',
'microwave',
'drying_machine',
'dish_washer',
'television']}],
'rooms': [{'bathroom': True, 'floor': 2},
{'bedroom': True, 'floor': [2, 3], 'needs_renovation': 'EXCLUDE'}],
'value': [{'family_unit': 'UNKNOWN', 'occupied': True, 'sale_price': 9003.01}],
'walls': [{'color': 'WHITE', 'max_height': 3, 'min_height': 18}]}
